My simple calculator

https://codepen.io/AK-47/pen/QqQEWZ?editors=1011

Hello friends, i need some help with implementing square in my simple calculator…What i mean is let’s say if you type the number 5 so the result will be 25 or type 7 the result will be 49 and so on, i got stuck on it, i don’t know why my function does not want to work…Thank you

A couple of things. First off, learn to check your console. Don’t even bother trying to debug code until you’ve cleared the console of errors. If you hit ctrl-shft-i (or whatever it is on your system/browser) the browser console will pop up and tell you that jQuery needs to be loaded before Bootstrap in your JS. I also see that you are trying to load two different versions of Bootstrap. Why?

To your code, once I cleared up those things, my first instinct is to put in console.log statements to see what is happening. (Seriously, console is your best friend.) When I put one in your squaring function,

  function getSqrt(i){
    console.log(i)
    var a = i * i;
    answer=a;
    $("#steps").text(eval(answer))
  }

I find that i is undefined. That’s because you never pass it anything. When you call it,

getSqrt();

you don’t send a value.

Some other thoughts:

  • You could clean up some of those if/else statements with some switch statements.

  • The eval() is considered by many to be bad practice and potentially a security risk.

  • Format your code as you go. Your code isn’t terrible but there are a few odd spots. In codepen you can actually just select everything (ctrl-a) and then shft-tab will regularlize all your indenting. I found it difficult to follow your code at points.

1 Like

Thank you so much for the clear and deep explanation and the lessons as well.You are amazing

Thank you so much for the clear and deep explanation and the lessons as well.You are amazing.

You’re right where I was 6 months ago. If you keep at it, in no time, you’ll be handing out advice.