Skip to content

Instantly share code, notes, and snippets.

@tennisonchan
Last active April 4, 2017 21:30
Show Gist options
  • Save tennisonchan/80ea3a7c7a79862765c0153be5caa7b8 to your computer and use it in GitHub Desktop.
Save tennisonchan/80ea3a7c7a79862765c0153be5caa7b8 to your computer and use it in GitHub Desktop.
StrangeThingsJS
var bar = "bar";
function foo(str) {
eval(str);
console.log(bar);
}
foo("var bar = 42;");
// 42
// js engine to not able to optimize the local and global scopes lookup when using eval
// as a result, it will be slower
// setTimeout with passing in a string using eval underneath
function foo() {
bar = 'baz';
}
foo();
console.log(window.bar);
// 'baz', even though we didn't declare bar in global scope
function foo2() {
'use strict';
bar2 = 'baz';
}
foo2();
// Uncaught ReferenceError: bal is not defined
function foo(bar) {
if(bar) {
console.log(baz);
// ReferenceError
let baz = 'baz';
}
}
foo(1)
['1', '2', '3'].map(parseInt)
// [1, NaN, NaN]
['1', '2', '3'].map(parseFloat)
// [1, 2, 3]
['1', '2', '3'].map(Number)
// [1, 2, 3]

Scope

Lexical Scope

Hoist

function foo () {
console.log(this.bar);
}
var bar = 'bar1';
var a = { bar: 'bar2', foo: foo };
var b = { bar: 'bar3', foo: foo };
foo(); // 'bar1'
a.foo(); // 'bar2'
b.foo(); // 'bar3'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment