JavaScript Flashcards
Accessing array elements
array[index]
Example:
var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37];
primes[0]; // 2
primes[3]; // 7
primes[150]; // undefined
Array literals
var arrayName = [element0, element1, …, elementN]
Example:
var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37];
var junk = [10, “Hello”, Math, console, { lots: “of different types” }];
Multi-dimensional arrays
var multidimensionalArray = [[1,2,3],[4,5,6],[7,8,9]] // two dimensions, 3x3
Array constructor
Example 1:
var myArray = new Array(45 , "Hello World!" , true , 3.2 , undefined); console.log(myArray);
Example 2:
var stuff = new Array();
stuff[0] = 34;
stuff[4] = 20;
stuff // [34, undefined, undefined, undefined, 20]
Accessing nested array elements
array[index][index]….
Example:
var myMultiArray = [
[1,2,3,4,5, [1,2,3,4,5] ],
[6,7,8,9,10 , [1,2,3,4,6] ],
[11,12,13,14,15 , [1,2,3,4,5] ],
[16,17,18,19,20, [1,2,3,4,5] ]
];
console.log( myMultiArray[1][5][4] ); //Outputs 6 , the value in the last element of the last element of the second element of myMultiArray.
Boolean literals
true
false
Boolean logical operators
if ( true && false )alert("Not executed!"); //because the second expression is false
if( false || true )alert("Executed!"); //because any one of the expression is true
if( !false )alert("Executed!"); // because !false evaluates to true
!!true // remains true
Operator Precedance
// Brackets - have the highest precedence // ! - lower than Brackets // && - lower than ! // || - the lowest
if(true && !!false || true)alert(“Guess again ??”);
/* Executed , here is the evaluation process-
true && !!false || true - becomes
true && false || true - (no brackets present , so ! evaluated ) becomes
false || true - (then && evaluated) which becomes true */
Operator Associativity
Determines the order in which operators of the same precedence are processed. For example, consider an expression: a * b * c . Left-associativity (left-to-right) means that it is processed as (a * b) * c, while right-associativity (right-to-left) means it is interpreted as a * (b * c). */
// Brackets , && , || have left to right associativity // ! has right to left associativity // So ,
!false && !!false //false // evaluated in the manner - !false && false - true && false - false
Comparison operator
x === y // returns true if two things are equal
x !== y // returns true if two things are not equal
x <= y // returns true if x is less than or equal to y
x >= y // returns true if x is greater than or equal to y
x < y // returns true if x is less than y
x > y // returns true if x is greater than y
Other ways of deriving true and false
if(1)console.log(“True!”); // output True! , since any non-zero number is considered to be true
if(0)console.log(“I doubt if this gets executed”); // not executed , since 0 is considered to be false
if(“Hello”)alert(“So, any non-empty String is also true.”); //Gets executed
if(““)alert(“Hence , an empty String is false”); // Not executed
Difference between == and ===
== does just value checking ( no type checking ) , whereas , === does both value checking and type checking . It is always advisable that you never use == , because == often produces unwanted results
Example:
‘1’ == 1 //true (same value)
‘1’ === 1 // false (not the same type)
true == 1 // true (because 1 stands for true ,though it’s not the same type)
true === 1 // false (not the same type)
Comments
// Single line
/*
Multi
line
*/
console.log
Prints to the console, good for debugging.
Example:
console.log(‘Poker night!’);
console.time
console. time(timerName);
console. timeEnd(timerName);
Example:
console.time(“My Math”);
var x = 5 + 5;
console.log(x);
console.timeEnd(“My Math”);
console.log(“Done the math.”);
/* Output:
10
My Math: (time taken)
Done the math.
function
function name(argument1 , argument2 …. argumentN){
statement1;
statement2;
statementN;
}
Example:
function greet(name) { return "Hello" + name + "!"; }
function calling
functionName(argument1, argument2, …, argumentN);
function hoisting
hoistedFunction(); // Hello! I am defined immediately!
notHoistedFunction(); // ReferenceError: notHoistedFunction is not defined
function hoistedFunction () { console.log('Hello! I am defined immediately!'); }
var notHoistedFunction = function () { console.log('I am not defined immediately.'); }
if
if (condition) { // code that runs if the condition is true }
else
if (condition) { // statement1: code that runs if condition is true } else { // statement2: code that runs if condition is false }
else if
if (condition1) {
statement1;
} else if (condition2) {
statement2;
} else {
statement3;
}
for loops
for ([var i = startValue];[i \< endValue]; [i+=stepValue]) { // Your code here }
Example:
for (var i = 0; i \< 5; i++) { console.log(i); // Prints the numbers from 0 to 4 }
var i; // “outsourcing” the definition
for (i = 10; i >= 1; i–) {
console.log(i); // Prints the numbers from 10 to 1
}
for loops: all three statements are ____
/* Note that all of the three statements are optional, i.e. , */
var i = 9;
for(;;){
if(i === 0)break;
console.log(i);
i–;
}
//This loop is perfectly valid.
while loops
var x = 0; while (x \< 5) { console.log(x); // Prints numbers from 0 to 4 x++; }
var x = 10;
while (x <= 5) {
console.log(x); // Won’t be executed
x++;
}
do while
do { // Your code here } while (condition);
Example:
var x = 10; do { console.log(x); // Prints 10 x++; } while (x \<= 5);
random
Math.random(); // A random number between 0 and 1.
floor
Math.floor(expression)
Returns the largest integer less than or equal to a number.
Math.floor(9.99); // 9
Math.floor(1 + 0.5); // 1
Math.floor(Math.random() * X + 1); // Returns a random number between 1 and X
Returns base raised to exponent.
Math.pow(base,exponent)
ceil
Math.ceil(expression)
Returns the smallest integer greater than or equal to a number.
Math.ceil(45.4); // 46
Math.ceil(4 - 1.9); // 3
Returns the ratio of the circumference of a circle to its diameter
Math.PI
Example:
Math.round(Math.PI); // rounds the value of PI ,gives 3
Math.ceil(Math.PI); // 4
Returns the square root of a number.
Math.sqrt(expression)
Modulus
Returns the remainder left after dividing the left hand side with the right hand side.
number1 % number2
Example:
14 % 9 // returns 5
isNaN
isNaN([value])
Returns true if the given number is not a number , else returns false.
var user_input = prompt(“Enter a number”); // Enter “a number”
if(isNaN(user_input))
alert(“I told you to enter a number.”);
//alert executed , since “a number” is not a number
//Another important thing:
if( isNaN(“3”) )
alert(“bad”);
//Not executed , because the string “3” gets converted into 3 ,and 3 is a number
Prefix/Postfix Increment/Decrement
++variable
–variable
variable++
variable–
var x = 15; // x has a value of 15
var y = x++;
// since it is postfix , the value of x (15) is first assigned to y and then the value of x is incremented by 1
console.log(y); //15
console.log(x); //16
var a = 15; // a has a value of 15
var b = ++a;
// since it is prefix , the value of a (15) is first incremented by 1 and then the value of x is assigned to b
console.log(b); //16
console.log(a); //16
Object Literals
{
“property 1”: value1,
property2: value2,
number: value3
}
Example:
var obj = { name: "Bob", married: true, "mother's name": "Alice", "year of birth": 1987, getAge: function () { return 2012 - obj["year of birth"]; }, 1: 'one' };
Property Access
name1[string]
name2.identifier
Example:
obj[‘name’]; // ‘Bob’
obj. name; // ‘Bob’
obj. getAge(); // 24
Classes
A class can be thought of as a template to create many objects with similar qualities.
SubClass.prototype = new SuperClass();
var Lieutenant = function (age) {
this.rank = “Lieutenant”;
this.age = age;
};
Lieutenant.prototype = new PoliceOfficer();
Lieutenant.prototype.getRank = function () {
return this.rank;
};
var John = new Lieutenant(67);
John.getJob(); // ‘Police Officer’
John.getRank(); // ‘Lieutenant’
John.retire(); // true
confirm
confirm(“message”) //returns true if confirmed, false otherwise
Example:
if ( confirm(“Are you sure you want to delete this post?”) ) {
deletePost();
}
prompt
prompt(message,value)
prompt(message,value) // value is a string containing the default value displayed in the text input field.
Displays a dialog with an optional message prompting the user to input some text. If the user clicks the “Cancel” button , null is returned.
Changes the cases of all the alphabetical letters in the string.
string. toUpperCase()
string. toLowerCase()
Removes whitespace from both ends of the string.
string.trim();
Example:
” a “.trim(); // ‘a’
“ a a “.trim(); // ‘a a’
Returns a string with the first match substring replaced with a new substring
.replace();
“original string”.replace(“original”, “replaced”); // returns “replaced string”
Returns the specified character from a string.
.charAt()
string.charAt(index) // index is an integer between 0 and 1 less than the length of the string.
“Hello World!”.charAt(0); // ‘H’
“Hello World!”.charAt(234); // ‘’