Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to unbound JavaScript literals?

Tags:

javascript

What happens to JavaScript literals (strings, numbers) that are not bound (aka assigned) to a variable ?

// A comment
"Practically, also a comment"
var assigned = "something"
53
423.0022 
NaN
"does it impact performance"
// or is it treated just like a comment?

The browser appears to ignore them, but I couldn't find a specific rule in the spec

like image 564
Christoph Avatar asked Jun 29 '17 20:06

Christoph


2 Answers

These are "expression statements". Such expressions are evaluated, but since they are not assigned, their value is not stored. JavaScript engines are likely to detect those that have no side effects, and eliminate them as if they were never there.

But still at least one of those has an effect:

 "use strict";

This has the meaning of a JavaScript directive

From the EcmaScript specification:

A Use Strict Directive is an ExpressionStatement in a Directive Prologue whose StringLiteral is either the exact code unit sequences "use strict" or 'use strict'.

Also note that other string literals may have a special meaning when used in the directive prologue:

Implementations may define implementation specific meanings for ExpressionStatement productions which are not a Use Strict Directive and which occur in a Directive Prologue.

like image 124
trincot Avatar answered Sep 27 '22 20:09

trincot


It's just an expression statement that evaluates - without side effects - to a value that is discarded.

You can see it's the result of the statement if you try this in eval or a REPL.

like image 42
Bergi Avatar answered Sep 27 '22 21:09

Bergi