Knowledge in Java Collection

JavaScript Assignment

JavaScript AssignmentThe = assignment operator assigns a value to a variable.Assignmentvar x = 10;The += assignment operator adds a value to a variable.Assignmentvar x = 10;x += 5;The -= assignment operator subtracts a value from a variable.Assignmentvar x = 10;x -= 5;The *= assignment operator multiplies a variable.Assignmentvar x = 10;x *= 5;The /= assignment divides a variable.Assignmentvar x = 10;x /= 5;The %= assignment operator assigns a remainder to a variable.Assignmentvar x = 10;x %= 5;

JavaScript Data Types

JavaScript Data TypesJavaScript variables can hold many data types: numbers, strings, objects and more:var length = 16;                               // Numbervar lastName = "Johnson";                      // Stringvar x = {firstName:"John", lastName:"Doe"};    // ObjectThe Concept of Data TypesIn programming, data types is an important concept.To be able to operate on variables, it is important to know something about the type.Without data types, a computer cannot safely solve this:var x = 16 + "Volvo";Does it make any sense to add "Volvo" to sixteen? Will it produce an error or will it produce a result?JavaScript will treat the example above as:var x = "16" + "Volvo";When adding a number and a string, JavaScript will treat the number as a string.Examplevar x = 16 + "Volvo";Examplevar x = "Volvo" + 16;JavaScript evaluates expressions from left to right. Different sequences can produce different results:JavaScript:var x = 16 + 4 + "Volvo";Result:20VolvoJavaScript:var x = "Volvo" + 16 + 4;Result:Volvo164

JavaScript Types are Dynamic

JavaScript Types are DynamicJavaScript has dynamic types. This means that the same variable can be used to hold different data types:Examplevar x;           // Now x is undefinedx = 5;           // Now x is a Numberx = "John";      // Now x is a StringJavaScript StringsA string (or a text string) is a series of characters like "John Doe".Strings are written with quotes. You can use single or double quotes:Examplevar carName1 = "Volvo XC60";   // Using double quotesvar carName2 = 'Volvo XC60';   // Using single quotesYou can use quotes inside a string, as long as they don't match the quotes surrounding the string:Examplevar answer1 = "It's alright";             // Single quote inside double quotesvar answer2 = "He is called 'Johnny'";    // Single quotes inside double quotesvar answer3 = 'He is called "Johnny"';    // Double quotes inside single quotesYou will learn more about strings later in this tutorial.JavaScript NumbersJavaScript has only one type of numbers.Numbers can be written with, or without decimals:Examplevar x1 = 34.00;     // Written with decimalsvar x2 = 34;        // Written without decimalsExtra large or extra small numbers can be written with scientific (exponential) notation:Examplevar y = 123e5;      // 12300000var z = 123e-5;     // 0.00123Try it yourself »You will learn more about numbers later in this tutorial.JavaScript BooleansBooleans can only have two values: true or false.Examplevar x = 5;var y = 5;var z = 6;(x == y)       // Returns true(x == z)       // Returns falseBooleans are often used in conditional testing.You will learn more about conditional testing later in this tutorial.JavaScript ArraysJavaScript arrays are written with square brackets.Array items are separated by commas.The following code declares (creates) an array called cars, containing three items (car names):Examplevar cars = ["Saab", "Volvo", "BMW"];

JavaScript Objects

JavaScript ObjectsJavaScript objects are written with curly braces {}.Object properties are written as name:value pairs, separated by commas.Examplevar person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};The object (person) in the example above has 4 properties: firstName, lastName, age, and eyeColor.You will learn more about objects later in this tutorial.The typeof OperatorYou can use the JavaScript typeof operator to find the type of a JavaScript variable.The typeof operator returns the type of a variable or an expression:Exampletypeof ""            // Returns "string"typeof "John"         // Returns "string"typeof "John Doe"     // Returns "string"Exampletypeof 0             // Returns "number"typeof 314            // Returns "number"typeof 3.14           // Returns "number"typeof (3)            // Returns "number"typeof (3 + 4)        // Returns "number"

Difference Between Undefined and Null

Difference Between Undefined and Nullundefined and null are equal in value but different in type:typeof undefined           // undefinedtypeof null                // objectnull === undefined         // falsenull == undefined          // true

Primitive Data

Primitive DataA primitive data value is a single simple data value with no additional properties and methods.The typeof operator can return one of these primitive types:stringnumberbooleanundefinedExampletypeof "John"              // Returns "string"typeof 3.14                // Returns "number"typeof true                // Returns "boolean"typeof false               // Returns "boolean"typeof x                   // Returns "undefined" (if x has no value)Complex DataThe typeof operator can return one of two complex types:functionobjectThe typeof operator returns "object" for objects, arrays, and null.The typeof operator does not return "object" for functions.Exampletypeof {name:'John', age:34} // Returns "object"typeof [1,2,3,4]             // Returns "object" (not "array", see note below)typeof null                  // Returns "object"typeof function myFunc(){}   // Returns "function"

JavaScript Functions

JavaScript FunctionsA JavaScript function is a block of code designed to perform a particular task.A JavaScript function is executed when "something" invokes it (calls it).Examplefunction myFunction(p1, p2) {  return p1 * p2;   // The function returns the product of p1 and p2}JavaScript Function SyntaxA JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).The parentheses may include parameter names separated by commas:(parameter1, parameter2, ...)The code to be executed, by the function, is placed inside curly brackets: {}function name(parameter1, parameter2, parameter3) {  // code to be executed}Function parameters are listed inside the parentheses () in the function definition.Function arguments are the values received by the function when it is invoked.Inside the function, the arguments (the parameters) behave as local variables.A Function is much the same as a Procedure or a Subroutine, in other programming languages.

JavaScript Objects

JavaScript ObjectsReal Life Objects, Properties, and MethodsIn real life, a car is an object.A car has properties like weight and color, and methods like start and stop:JavaScript ObjectsYou have already learned that JavaScript variables are containers for data values.This code assigns a simple value (Fiat) to a variable named car:var car = "Fiat";Objects are variables too. But objects can contain many values.This code assigns many values (Fiat, 500, white) to a variable named car:var car = {type:"Fiat", model:"500", color:"white"};

Object Definition

Object DefinitionYou define (and create) a JavaScript object with an object literal:Examplevar person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};Spaces and line breaks are not important. An object definition can span multiple lines:Examplevar person = { firstName: "John", lastName: "Doe",  age: 50,  eyeColor: "blue"};

JavaScript Strings

JavaScript StringsA JavaScript string is zero or more characters written inside quotes.Examplevar x = "John Doe";You can use single or double quotes:Examplevar carName1 = "Volvo XC60";  // Double quotesvar carName2 = 'Volvo XC60';  // Single quotesYou can use quotes inside a string, as long as they don't match the quotes surrounding the string:Examplevar answer1 = "It's alright";var answer2 = "He is called 'Johnny'";var answer3 = 'He is called "Johnny"';String LengthTo find the length of a string, use the built-in length property:Examplevar txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";var sln = txt.length;

JavaScript String Methods

JavaScript String MethodsString methods help you to work with strings.String Methods and PropertiesPrimitive values, like "John Doe", cannot have properties or methods (because they are not objects).But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.String LengthThe length property returns the length of a string:Examplevar txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";var sln = txt.length;Finding a String in a StringThe indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string:Examplevar str = "Please locate where 'locate' occurs!";var pos = str.indexOf("locate");

IMP JS

Did You Notice?The two methods, indexOf() and search(), are equal?They accept the same arguments (parameters), and return the same value?The two methods are NOT equal. These are the differences:The search() method cannot take a second start position argument.The indexOf() method cannot take powerful search values (regular expressions).You will learn more about regular expressions in a later chapter.Extracting String PartsThere are 3 methods for extracting a part of a string:slice(start, end)substring(start, end)substr(start, length)The slice() Methodslice() extracts a part of a string and returns the extracted part in a new string.The method takes 2 parameters: the start position, and the end position (end not included).This example slices out a portion of a string from position 7 to position 12 (13-1):Examplevar str = "Apple, Banana, Kiwi";var res = str.slice(7, 13);The result of res will be:BananaRemember: JavaScript counts positions from zero. First position is 0.If a parameter is negative, the position is counted from the end of the string.This example slices out a portion of a string from position -12 to position -6:Examplevar str = "Apple, Banana, Kiwi";var res = str.slice(-12, -6);The result of res will be:BananaIf you omit the second parameter, the method will slice out the rest of the string:Examplevar res = str.slice(7);or, counting from the end:Examplevar res = str.slice(-12);