Skip to content

Instantly share code, notes, and snippets.

@superzadeh
Last active October 3, 2017 08:55
Show Gist options
  • Save superzadeh/9ca8ad2d027527d0953efa7c268edefd to your computer and use it in GitHub Desktop.
Save superzadeh/9ca8ad2d027527d0953efa7c268edefd to your computer and use it in GitHub Desktop.
demystify javascript for C# developpers #tags: javascript, training

JavaScript demystified

Below are "my words", as I understand them. They are by no mean a reference, but my hope is that they can somehow help you understand some key elements of the JavaScript language.

For far more detailed and accurate explanations, refer to Kyle Simpson's series "You don't know JS yet".

Understanding "==="

A strongly weakly typed language

  • JavaScript is a weakly typed language
    • Variables are not declared with a type
    • The type of a variable can change when it is assigned
    • Every variable has a type
  • JavaScript does type coercion
    • When comparing two variables of different types, JavaScript converts them to the same type

Demo: http://jsfiddle.net/ntzhrjuu/13/

Remember

  • Test against falsy values, not just null or undefined
  • When needed, use the === and !== operators to check against:
    • Value of the variables
    • Types of the variables

-If you need to check the type of a variable, use typeof

if(myvar && typeof(myvar) === 'string')
{ 
  // your variable is not falsy and it is a string }
}

Understanding "this"

An interpreted and compiled language

JavaScript is an interpreted language

  • A script is loaded in a browser and executed
  • There is not need to compile it in binary format

JavaScript is compiled

  • Each time it is executed, a script is compiled and optimized

Lexical scope VS Dynamic scope

JavaScript has two scopes

  • Lexical scope: set at authoring time, when you write the script
  • Dynamic scope: set at runtime, when the script being executed

The variable this belongs to the Dynamic scope

  • The value of this will be determined at runtime
  • In most cases, this will have the value of its function’s call site
  • Except when constructing an object, where this will be the object itself

Demo: https://jsfiddle.net/c6tfxjms/8/

Remember

Use lexical capture to prevent binding issues

  • Inside the constructor, declare a variable and use it instead of this:
var self = this;
self.this.value = 'wow, much string, such value';
this.ShowMyLocation = function () { console.log(self.value) } );

Use explicit binding on existing code that cannot be refactored After the function declaration or when it is passed as a delegate, add the following code (in red):

var bar = new ViewModels.foo();
$("#clickme").click(bar.ShowMyLocation.bind(bar));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment