JavaScript in a nutshell

JavaScript

JavaScript (JS) is a lightweight, interpreted, programming language with first-class functions.
While it is most well-known as the scripting language for web pages, many non-browser environments also use
it, such as node.js and Apache CouchDB. JS is a prototype-based, multi-paradigm, dynamic scripting language,
supporting object-oriented, imperative, and declarative (e.g. functional programming) styles.

Filename extension .js
Mime type application/javascript

// single line comments start with two slashes /* multi line comments start with a slash star and end with a star slash */
// a statement can be terminated by a semicolon ( ; ) doSometing(); //but it's not required doSomething() // place it when having multiple statements non a single line doSometing(); doSometing()
'use strict' // at the beginning of a file or a function enforces Strict Mode

Strict Mode

numbers

/* JavaScript does not define different types of numbers, like integers, short, long, floating-point etc. JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard. This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63 */ 8 // = 8 2.5 // = 2.5 5 + 5 // = 10 9 - 2 // = 7 5 * 3 // = 15 5 / 2 // = 2.5 10 % 3 // = 1 0.1 + 0.2 // = 0.30000000000000004 // soliving above like this (0.2 * 10 + 0.1 * 10) / 10 // = 0.3 // bitwise operations can be done as well 1 << 2 // = 4 // the normal order of operations work 5 + 2 * 3 // = 11 /* by default all numbers are in base 10 */ // hexadecimal 0x16 // = 22 // converting to hexadecimal // value.toString( base ) 0x16.toString(10) // = 22 (22).toString(16) // = 22 // !!! as some might have guessed toString() will return a string. 0x16.toString(10) + 10 // = 2210 // the simplest way to fix this is to multiply it with 1 // * 1 will alway return a number type 0x16.toString(10) * 1 + 10 // = 32 /* special cases (all are of type number) */ Infinity // result of e.g. 1/0 -Infinity // result of e.g. -1/0 NaN // stands for 'Not a Number' // result of 0 / 0, but also of 10 * 'wiki' isNaN(10 / 'wiki') // = true // depending on the environment there is a `Math` library // including usful functions Math.min(42, 2, 9) // = 2 Math.max(42, 2, 9) // = 42 Math.round(2.8) // = 3 Math.round(2.3) // = 2 Math.random() // a random number between 0 (inclusive) and 1 (exclusive) Math.PI // = 3.141592653589793 // ... and quit a bit more

rest of the types

// numbers as seen 5 /* booleans */ true false !true // = false // there's also `null` and `undefined` null // used to indicate a deliberate non-value undefined // used to indicate a value is not currently present /* strings begin and end with a double quote ( " ) or single quote ( ' ). special characters: \' single quote \t tab \" double quote \b backspace \\ backslash \f form feed \n new line \r carriage return */ 'I'm a string' 'I\'m a string as well' // length '13 characters'.length // = 13 // concatenation 'Hello' + ' world!' // = 'Hello world!' '1, 2, ' + 3; // = '1, 2, 3' 'Hello ' + ['world', '!'] // = 'Hello world,!' // access characters in a string with `charAt` 'This is a string'.charAt(0) // = 'T' // ...use `substring` to get a string out of the string 'Hello world'.substring(0, 5) // = 'Hello'

variables, arrays andobjects

// variables are containers for storing data values. // JavaScript is dynamically typed, so you don't need to specify type var someVar = 'something' // if you leave the var keyword off, you won't get an error... someOtherVar = 10 // ...but your variable will be created in the global scope, not in the scope you defined it in // Variables declared without being assigned to are set to undefined. var someThirdVar // = undefined // if you want to declare a couple of variables, then you could use a comma // separator var someFourthVar = 2, someFifthVar = 4 // there's shorthand for performing math operations on variables: someVar += 5 // equivalent to `someVar = someVar + 5` = 10 someVar *= 10 // now someVar is 100 // and an even-shorter-hand for adding or subtracting 1 someVar++ // now someVar is 101 someVar-- // back to 100 // arrays are ordered lists of values, of any type var anArray = ['Hello', 45, true] // the values can be accessed with brackets ( [index] ); starting at 0 anArray[1] // = 45 // arrays are mutable and of variable length anArray.push('World') anArray.length // = 4 // add / modify at specific index anArray[3] = 'Hello' // JavaScript's objects are equivalent to 'dictionaries' or 'maps' in other // languages: an unordered collection of key-value pairs. var myObj = {key1: 'Hello', key2: 'World'} // Keys are strings, but quotes aren't required if they're a valid // JavaScript identifier. Values can be any type. var myObj = {myKey: 'myValue', 'my other key': 4} // Object attributes can also be accessed using the subscript syntax, myObj['my other key'] // = 4 // ... or using the dot syntax, provided the key is a valid identifier. myObj.myKey; // = 'myValue' // Objects are mutable; values can be changed and new keys added. myObj.myThirdKey = true // If you try to access a value that's not yet set, you'll get undefined. myObj.myFourthKey // = undefined

More about Objects ( JSON structurs) can be learned here JSON in a nutshell

printing

// prints in the default message style console.log('Hello World') // prints a red error message console.error('Ohh snap!') // printing warnings (usually yellow) console.warn('No so fast') // and blue informations console.info('Hello Universe!') // all these accept any kind and ammount of parameter console.log('the answers is', 42, [ {'the question?': 'I don\'t know'} ]) // depending on the environment css can be applied console.log('%c My message here', 'font-weight: bold; color: blue; padding:10px;')

comparing the types

// equality is === 1 === 1; // = true 2 === 1; // = false // === is type save 0 === '0' // = false 0 == '0' // = true // false, null, undefined, NaN, 0 and '' are falsy; everything else is truthy // !!! Note that 0 is falsy and '0' is truthy, even though 0 == '0' // 'false' is truthy as well '5' == 5; // = true null == undefined; // = true '5' === 5; // = false null === undefined; // = false // inequality is !== 1 !== 1; // = false 2 !== 1; // = true // More comparisons 1 < 10; // = true 1 > 10; // = false 2 <= 2; // = true 2 >= 2; // = true // chars can be compared with < and > 'a' < 'b'; // = true

control structures

// if the given expression is true, the statement or statements will be executed. Otherwise, they are skipped. if (true === false){ // do stuff } else if ( 1 == 2 && true ){ // do stuff } else boom() // brackets are optional when having only one statement // while structurs execute a given statement as long as the given expression is true while (true){ // An infinite loop! } // Do-while loops are like while loops, except they always run at least once. var input do { input = getInput() } while (!isValid(input)) // The `for` loop is the same as C and Java: // initialisation; continue condition; iteration. for (var i = 0; i < 5; i++){ // will run 5 times } // iterating over objects and arrays can be simplified // `for in` goes over the keys /indexes of the object / array. // !!! the execution order can be random var object = {first:5, second: 3, third: 9} for(var element in object) { console.log(element) // = first // second // third } // the `switch` statement checks for equality with `===` and works with any data type // use 'break' after each case // or the cases after the correct one will be executed too. var number = 4 switch (grade) { case 1: case 2: case 3: console.log('number is 1, 2 or 3') break case 4: console.log('it\'s 4') break default: console.log('well, it could be anything') }

functions

// JavaScript functions are declared with the `function` keyword function sayHello(name){ return "hello " + name } sayHello('john') // = 'hello john' // Note that the value to be returned must start on the same line as the // `return` keyword, otherwise you'll always return `undefined` due to // automatic semicolon insertion. function myFunction(){ return // <- semicolon automatically inserted here {thisIsAn: 'object literal'} } myFunction() // = undefined // JavaScript functions are first class objects, so they can be reassigned to // different variable names and passed to other functions as arguments - for // example, when supplying an event handler: function myFunction(){ // this code will be called in 5 seconds' time } setTimeout(myFunction, 5000) // !!! setTimeout isn't part of the JS language, but is provided by browsers and node.js. // Another function provided by browsers is setInterval function myFunction(){ // this code will be called every 5 seconds } setInterval(myFunction, 5000) // Function objects don't even have to be declared with a name - you can write // an anonymous function definition directly into the arguments of another. setTimeout(function(){ // this code will be called in 5 seconds' time }, 5000) // JavaScript has function scope; functions get their own scope but other blocks // do not. if (true){ var i = 5 } i // = 5 ... not undefined as you'd expect in a block-scoped language // This has led to a common pattern of "immediately-executing anonymous // functions", which prevent temporary variables from leaking into the global // scope. (function(){ var temporary = 5 // We can access the global scope by assigning to the "global object", which // in a web browser is always `window`. The global object may have a // different name in non-browser environments such as Node.js. window.permanent = 10 })() temporary // raises ReferenceError permanent // = 10 // One of JavaScript's most powerful features is closures and [Web Development](https://www.ingic.ae/website-development/ ). If a function is // defined inside another function, the inner function has access to all the // outer function's variables, even after the outer function exits. function sayHelloInFiveSeconds(name){ var prompt = "Hello, " + name + "!"; // Inner functions are put in the local scope by default, as if they were // declared with `var`. function inner(){ alert(prompt); } setTimeout(inner, 5000); // setTimeout is asynchronous, so the sayHelloInFiveSeconds function will // exit immediately, and setTimeout will call inner afterwards. However, // because inner is "closed over" sayHelloInFiveSeconds, inner still has // access to the `prompt` variable when it is finally called. } sayHelloInFiveSeconds("Adam")

Reference

w3schools www.w3schools.com
Learn X in Y minutes learnxinyminutes.com

History Oct 17, 2017