0

I was doing some reading about JavaScript and came across something called "use strict";. That's not what this question's about, it's simply an example of placing a string in code. What interested me was that I can place a string (or indeed, any other value) on its own line of code in JavaScript and it does absolutely nothing (from what I can tell). For example, as far as I'm aware, the following code has no purpose:

(function(){
    "random string";
    8;
    true;
    [1,2,3];
    { "key": "value" }
}())

Why can I do this and what purpose does it serve?

I also realised that functions that return a value effectively do this (am I correct?):

// Some code...

function doSomething() {
    // Do some stuff
    return true;
}

doSomething();

// Some more code...

Does that effectively evaluate to this?

// Some code...

function doSomething() {
    // Do some stuff
    return true;
}

true;

// Some more code...
Community
  • 1
  • 1
Robbie JW
  • 729
  • 1
  • 9
  • 22
  • `"random string"; 8; true; [1,2,3]; { "key": "value" };` all are valid JavaScript expressions. So, they are evaluated to the same values and ignored. – thefourtheye Mar 09 '14 at 11:30

1 Answers1

1

No programming language will completely protect you from doing pointless things. Could your examples be fixed? The first yes. But it would complicate the semantics of the language.

The below are considered "expressions". And the rule is that expressions can be placed anywhere in the code, "evaluate" to a value, and can be part of other expressions. Notice the func1() which is also an expression, and is useful.

"random string"
8
true
[1,2,3]
{ "key": "value" }
func1()

The second case... Yes this is what basically happens. It would also be possible to forbid functions explicitly returning a value to be called "alone". But there are plenty of cases where the function has a side-effect (ex changes the DOM, or changes an external variable), and the value it returns (ex whether it was successful, how many elements got changed) may, or may not be needed.

sabof
  • 8,062
  • 4
  • 28
  • 52
  • With regards to `func1()` being an expression, this means I could use `var foo = func1()` to capture whatever `func1()` returns, correct? – Robbie JW Mar 09 '14 at 12:05
  • And if the return value is not needed (for example, were a function to return `undefined`) then simply writing `func1();` would evaluate to `undefined;`? – Robbie JW Mar 09 '14 at 12:05