Values
Booleans, numbers,strings, arrays, etc. All values in JavaScript have properties. Each property has a key (or name) and a value. You can think of properties like fields of a record. You use the dot (.)operator to read a property: value.propKey > var str = 'abc'; > str.length
Primitive Values Versus Objects
JavaScript makes a somewhat arbitrary distinction between values: The primitive values are booleans, numbers, strings, null, and undefined. All other values are objects.
Undefined values
There are two special values, written null and undefined, that are used to denote the absence of a meaningful value. They are themselves values, but they carry no information.
Automatic type conversion
When an operator is applied to the wrong type of value, JavaScript will quietly convert that value to the type it wants,using a set of rules that often arent what you want or expect. This is called type coercion. The logical operators && and || handle values of different types in a peculiar way. They will convert the value on their left side to Boolean type in order to decide what to do, but depending on the operator and the result of that conversion, they return either the original left-hand value or the right-hand value.
Special numbers
There are three special values in JavaScript that are considered numbers but dont behave like normal number. Infinity -Infinity, represent the positive and negative infinities. NaN stands for not a number, even though it is a value of the number type.
Expressions and statements
A fragment of code that produces a value is called an expression. Every value that is written literally is an expression. An expression between parentheses is also an expression, as is a binary operator applied to two expressions or a unary operator applied to one. The simplest kind of statement is an expression with a semicolon after it. The = operator can be used at any time on existing variables to disconnect them from their current value and have them point to a new one.
The environment
The collection of variables and their values that exist at a given time is called the environment. When a program starts up, this environment is not empty. It always contains variables that are part of the language standard, and most of the time, it has variables that provide ways to interact with the surrounding system. For example, in a browser, there are variables and functions to inspect and influence the currently loaded website and to read mouse and keyboard input.
Functions
A lot of the values provided in the default environment have the type function. A function is a piece of program wrapped in a value. Such values can be applied in order to run the wrapped program. For example, in a browser environment, the variable alert holds a function that shows a little dialog box with a message. Executing a function is called invoking, calling, or applying it. You can call a function by putting parentheses after an expression that produces a function value.
The console.log function
The alert function can be useful as an output device when experimenting, but clicking away all those little windows will get on your nerves. Most JavaScript systems (including all modern web browsers and Node.js) provide a console.log function that writes out its arguments to some text output device. In browsers, the output lands in the JavaScript console. This part of the browser interface is hidden by default,but most browsers open it when you press F12. var x = 30; console.log("the value of x is", x); // the value of x is 30
Return values
When a function produces a value, it is said to return that value. Anything that produces a value is an expression in JavaScript, which means function calls can be used within larger expressions. Here a call to Math.min, which is the opposite of Math.max, is used as an input to the plus operator: console.log(Math.min(2, 4) + 100); // 102
Prompt and confirm
You can ask the user an OK/Cancel question using confirm. This returns a Boolean: true if the user clicks OK and false if the user clicks Cancel.
Control flow
When your program contains more than one statement, the statements are executed, predictably, from top to bottom.
Conditional execution
Executing statements in straight-line order isnt the only option we have. An alternative is conditional execution, where we choose between two different routes based on a Boolean value var theNumber = Number(prompt("Pick a number", "")); if (!isNaN(theNumber)) alert("Your number is the square root of " + theNumber * theNumber); With this modification, if you enter cheese, no output will be shown. The keyword if executes or skips a statement depending on the value of a Boolean expression. The deciding expression is written after the keyword, between parentheses, followed by the statement to execute. var num = Number(prompt("Pick a number", "0")); if (num < 10) alert("Small"); else if (num < 100) alert("Medium"); else alert("Large"); while and do loops Looping control flow allows us to go back to some point in the program where we were before and repeat it with our current program state. If we combine this with a variable that counts, we can do something like this: var number = 0; while (number <= 12) { console.log(number); number = number + 2; } var number = 0; while (number <= 12) { console.log(number); number = number + 2; }
Indenting Code
In JavaScript, these are not required. The role of the indentation inside blocks is to make the structure of the code stand out.
for loops
for (var number = 0; number <= 12; number = number + 2) console.log(number); The parentheses after a for keyword must contain two semicolons. The part before the first semicolon initializes the loop, usually by defining a variable. The second part is the expression that checks whether the loop must continue. The final part updates the state of the loop after every iteration
Breaking Out of a Loop
Break has the effect of immediately jumping out of the enclosing loop. Using the remainder (%) operator is an easy way to test whether a number is divisible by another number. If it is, the remainder of their division is zero. Updating variables succinctly Especially when looping, a program often needs to update a variable to hold a value based on that ariables previous value. counter = counter + 1; JavaScript provides a shortcut for this: counter += 1; Dispatching on a value with switch There is a construct called switch that is intended to solve such a dispatch in a more direct way.
Capitalization
fuzzyLittleTurtle Most JavaScript programmers capitalize every word except the first.
Defining a function
A function definition is just a regular variable definition where the value given to the variable happens to be a function var square = function(x) { return x * x; }; console.log(square(12)); // 144
Parameters and scopes
The parameters to a function behave like regular variables, but their initial values are given by the caller of the function, not the code in the function itself. An important property of functions is that the variables created inside of them, including their parameters, are local to the function. function myFunction( ) { alert( "My Function" ); }
Nested scope JavaScript distinguishes not just between global and local variables. Functions can be created inside other functions, producing several degrees of locality
Return values Quite often, you'll want to get something back from your functions. This value that you want to get back is called the return value in Javascript. The return value can be a string of text, a number, a Boolean value, or even objects. But they only return one value. You can pass values over to your functions. These values are called arguments, and they go between the round brackets of the function. If you have more than one value to pass over, you separated them with commas. Functions as values Function variables usually simply act as names for a specific piece of the program. Such a variable is defined once and never changed. Declaration notation There is a slightly shorter way to say var square = function. The function keyword can also be used at the start of a statement, as in the following: function square(x) { return x * x; } < script type="text/javascript" > function sayHello(name, age) { document.write (name + " is " + age + " years old."); } function square(number) { return number * number; } Function () Constructor The function statement is not the only way to define a new function; you can define your function dynamically using Function() constructor along with the new operator. Function Literals JavaScript 1.2 introduces the concept of function literals which is another new way of defining functions. A function literal is an expression that defines an unnamed function.
Javascript Comparison Operators
!= Is not equal to > Greater Than < Less Than >= Greater Than or equal to <= Less Than or equal to === Is exactly like and is of the same variable type as
Binary Logical Operators
Binary logical operators in JavaScript are short-circuiting. That is, if the first operand suffices for determining the result, the second operand is not evaluated. For example, in the following expressions, the function foo() is never called: false && foo() true || foo() And (&&) If the first operand is falsy, return it. Otherwise, return the second operand. Or (||) If the first operand is truthy, return it. Otherwise, return the second operand. Equality Operators JavaScript has two kinds of equality: Normal, or lenient, (in)equality: == and != Strict (in)equality: === and !== Numbers All numbers in JavaScript are floating-point: > 1 === 1.0 tru Operators JavaScript has the following arithmetic operators: Addition: number1 + number2 Subtraction: number1 - number2 Multiplication: number1 * number2 Division: number1 / number2 Remainder: number1 % number2 Increment: ++variable, variable++ Decrement: --variable, variable-- Negate: -value Convert to number: +value
Unary operators
Not all operators are symbols. Some are written as words. One example is the typeof operator, which produces a string value naming the type of the value you give it. console.log(typeof 4.5) // number console.log(typeof "x") // string
Logical operators
Operators you will want to use with your IF Statements are the logical ones. The logical operators give you more options for your IF statements. && Two ampersands mean AND || Two pipe characters mean OR ! One exclamation mark/point means NOT There are also some operations that can be applied to Boolean values themselves. JavaScript supports three logical operators: and, or, and not. The && operator represents logical and. It is a binary operator, and its result is true only if both the values given to it are true. console.log(true && false) // false console.log(true && true) // true The || operator denotes logical or. It produces true if either of the values given to it is true. console.log(false || true) // true console.log(false || false) // false Not is written as an exclamation mark (!). It is a unary operator that flips the value given to it-!true produces false and !false gives true.
The Ternary Operators
If you want a quick IF statement then you can use something called a ternary expression. This uses a question mark ( ? ) and a colon ( : ). The syntax is this: var result = condition_to_test ? "TRUE" : "FALSE"; Here's a coding example: var over_eighteen = true; var result = over_eighteen ? "Truth" : "False"; document.write(result);

Javascript is what's known as a sequential programming language. This means that each and every line of code is executed from top to bottom. Quite often, however, you don't want every line to execute - you'll want more control over the way your programmes work. One way to control the flow of your code is with conditional logic. Conditional logic is all about what happens IF a condition is met or not met.
Block statement
{ statement_1; . . statement_n; }
Conditional statements
if...else statement switch statement
Exception handling statements
You can throw exceptions using the throw statement and handle them using the try...catch statements. The try...catch statement marks a block of statements to try, and specifies one or more responses should an exception be thrown. If an exception is thrown, the try...catch statement catches i
Loops and iterations
for statement The syntax of for loop is JavaScript is as follows: for (initialization; test condition; iteration statement){ Statement(s) to be executed if test condition is true } while statement The most basic loop in JavaScript is the while loop while (expression){ Statement(s) to be executed if expression is true } do...while statement The do...while loop is similar to the while loop except that the condition check happens at the end of the loop if statement if...else statement if...else if... statement label statement A label can be used with break and continue to control the flow more precisely. A label is simply an identifier followed by a colon that is applied to a statement or a block of code. break statement break; // breaks out of loop completely continue statement The continue statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block. for...in statement The for...in loop is used to loop through an object's properties for...of statement return statement A JavaScript function can have an optional return statement. This is required if you want to return a value from a function. The if statement has a then clause and an optional else clause that are executed depending on a boolean condition. if (myvar === 0) { // then } if (myvar === 0) { // then } else { // else } The do-while loop continues looping over its body while its condition holds. As the condition follows the body, the body is always executed at least once: do { // ... } while (condition); In all loops: break leaves the loop, continue starts a new loop iteration.
Expressions and operators
Arithmetic operators + - * / % ++ -- % Assignment operators = += -= /= Comparison operators = = (Equal) != (Not Equal) < > >= <= Bitwise operators & (Bitwise AND) | (BitWise OR) ^ (Bitwise XOR) ~ (Bitwise Not) << (Left Shift) >> (Right Shift) >>> (Right shift with Zero) Logical operators && (Logical AND) || (Logical OR) ! (Logical NOT String operators Conditional (ternary) operator ? : If Condition is true? Then value X : Otherwise value Y Comma operator Unary operators Relational operator typeof Operator
Expressions and operators
Arithmetic operators + - * / % ++ -- % Assignment operators = += -= /= Comparison operators = = (Equal) != (Not Equal) < > >= <= Bitwise operators & (Bitwise AND) | (BitWise OR) ^ (Bitwise XOR) ~ (Bitwise Not) << (Left Shift) >> (Right Shift) >>> (Right shift with Zero) Logical operators && (Logical AND) || (Logical OR) ! (Logical NOT String operators Conditional (ternary) operator ? : If Condition is true? Then value X : Otherwise value Y Comma operator Unary operators Relational operator typeof Operator
Strings
Strings can be created directly via string literals. Those literals are delimited by single or double quotes. The backslash (\) escapes characters and produces a few control characters. Here are some examples: 'abc' "abc" 'Did she say "Hello"?' "Did she say \"Hello\"?" If you need to change the case of a string of text you can use the two inbuilt methods toUpperCase and toLowerCase. The indexOf method tells you if a string of text contains a particular character, the @ sign in an email address for example. It won't check every occurrence of the character, but just the first one. If you want the character returned rather than its position number then you can use the Javascript string method charAt. var character = email.charAt( at_sign ); Sometimes, you want to grab characters from a string. For example, you can grab the last four letters from an email address and see if they end in .com. You can do this with the Javascript method substr. You can split up strings of text with the Javascript split method. In between the round brackets of split you type an optional delimiter. The delimiter is how the various parts of the string are separated. This might be with a comma, a semicolon, a space, etc. The delimiter needs to go between quote marks. When you split a string you turn it into an array. The Javascript join Method You can join strings of text together with the join method.
String Operators
Strings are concatenated via the plus (+) operator, which converts the other operand to a string if one of the operands is a string. String Methods Strings have many useful methods > 'abc'.slice(1) // copy a substring 'bc > '\t xyz '.trim() // trim whitespace 'xyz' > 'mjlnir'.toUpperCase() 'MJLNIR' > 'abc'.indexOf('b') // find a string 1 > 'abc'.indexOf('x') -1