Console.log()

Hello I was testing on this excersice and playing around.

Link: https://www.codecademy.com/courses/introduction-to-javascript/lessons/introduction-to-javascript/exercises/math-operators

So I typed
console.log(65 / 240 + " Hello " + (23 + 4));
And It printed at the last one: 0.2708333333333333 Hello 27

but when I type this

console.log(65 / 240 + " Hello " + 23 + 4);

It prints out at the end: 0.2708333333333333 Hello 234

Why?

1 Like

Welcome to the forums!
The parenthesis I’m pretty sure.

  1. console.log(65 / 240 + " Hello " + (23 + 4));
    First the computer logs 65 / 240 which gives you: 0.2708333333333333
    Then it logs Hello.
    Lastly, because of the parenthesis it will add 23 + 4, then log that at the end of "Hello" since you’re concatenating them.
    Which would give you 0.2708333333333333 Hello 27
  2. console.log(65 / 240 + " Hello " + 23 + 4);
    First the computer does 65 / 240 which gives you: 0.2708333333333333
    Then it logs Hello.
    Now, since you don’t have parenthesis, usually if you do:
    (An example) console.log(7) it would log 7. So it logs 23 and since you did +4, adds 4 to the end of 23. Giving you 234.
1 Like

To say it a different way, the inner parenthesis always get computed first. So (23 + 4) is always 27, but 'hello' + 23 is hello23. This is because when you try to add different types, the compiler will try to interpret what you meant (here it converts 23 to a string).

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.