JavaScript, often abbreviated as JS, is a high-level, dynamic, weakly typed, object-based, multi-paradigm, and interpreted programming language.
Single line comments start with //. For multi-line commands, you use /* ... */
// This is a single line comment
/*
And this is
a multi-line
comment
*/JavaScript is case-sensitive. This means that
Hello()is not the same asHELLO()orhello()
You can create variables using var, let, const (the last two ones are available only in ES6). Variable names can't start with a number or contain spaces. They can contain letters, numbers, underscores, or $. Variable names are case sensitive.
// This is how you define a variable
// `x` will be `undefined`
var x;
// Declare a constant (the convention is to use CAPS for constants)
const FOO = 42;
// Declare another two variables, using `var` and `let`
var hello = 'world';
let bar = 'baz';Variables don't have a type. As long as they are not constants, you can change their data:
let foo = 42;
foo = 'bar';
foo
// => 'bar'In JavaScript the use of semicolons is optional, as a new line indicates the end of the statement.
They are pretty similar, but unlike var, let declares a block scope local variable, optionally initializing it to a value. let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. The var keyword which defines a variable to an entire function regardless of block scope.
var a = 42;
if (true) {
var b = 7;
let c = 123;
}
// Obviously, we can access the `a` variable
console.log(a);
// => 42
// We can access `b` as well, even it was assigned in the
// if block (see below what happens if the expressions is
// false).
console.log(b);
// => 7
// We cannot access `c` here because it was declared using
// `let`, inside of the `if` block, therefore it's only
// accessible in the `if` block.
console.log(c);
// => Error: c is not definedJavaScript is a loosely typed language. This means that you can use the same variable for different types of information
Notice how in the first example below, we get the final value of i (because we print it after one second). In the other examples let does that for us, the i value inside of the setTimeout (after one second) is the current value of i when the setTimeout was called.
for (var i = 0; i < 7; ++i) {
setTimeout(function () {
console.log(i);
// => 8
// => 8
// => 8
// => 8
// => 8
// => 8
// => 8
// => 8
}, 1000);
}
for (let i = 0; i < 7; ++i) {
setTimeout(function () {
console.log(i);
// => 0
// => 1
// => 2
// => 3
// => 4
// => 5
// => 6
// => 7
}, 1000);
}A literal is a hard coded value.
One time initialisation. You can use it for variables which values remain the same.
const PI = 3.14;
PI = 3;
// => TypeError: Assignment to constant variable.Note, this won't freeze the objects:
// Create an object
const myObj = { foo: 'bar' };
// Update the `foo` field
myObj.foo = 42;
// Add a new field
myObj.hello = 'world';
myObj
// => { foo: 42, hello: 'world' }
// Though, if you try to reset the whole thing, you can't
myObj = {};
// => TypeError: Assignment to constant variable.let foo = 42;
if (foo > 40) {
// do something
} else {
// do something else
}let planet = 'Earth';
switch (planet) {
case "Mercury":
case "Venus":
console.log("Too hot here.");
break;
case 'Earth' :
console.log("Welcome home!");
break;
case 'Mars' :
console.log("Welcome to the other home!");
break;
case "Jupiter":
case "Saturn":
case "Uranus":
case "Neptune":
case "Pluto":
console.log("You may get gold here.");
break;
default:
console.log("Seems you found another planet.");
break;
}This will print all the integers from 1 to 42.
for (var i = 1; i <= 42; ++i) {
console.log(i);
}Using for ... in ... can be used to iterate object keys:
var name = {
first: "Johnny",
last: "B."
};
for (var key in name) {
if (name.hasOwnProperty(key)) {
console.log(key, name[key]);
// "first", "Johnny"
// "last", "B."
}
}In ES6 there is a for ... of ... as well. It's pretty neat since it iterates any iterable objects (arrays, strings etc).
let numbers = [-1, 7, 42, 64];
for (let num of numbers) {
console.log(num);
}
// -1
// 7
// 42
// 64
var country = "Bangladesh";
for(let letter of country) {
console.log(letter);
}
// B
// a
// n
// g
// l
// a
// d
// e
// s
// hvar i = 1;
while (i <= 42) {
console.log(i);
++i;
}var i = 0;
do {
++i;
console.log(i);
} while (i < 42);Primitive types are types provided by the system, in this case by JavaScript. Primitive type for JavaScript are Booleans, numbers and text. In addition to the primitive types, users may define their own classes. The following ones, are primitives:
- Booleans:
false,true - Numbers:
42,3.14,0b11010,0x16,NaN - Strings:
'Earth',"Mars" - Special Values:
undefined,null - Symbol (new in ECMAScript 6). A unique and immutable primitive value and may be used as the key of an Object property
Object refers to a data structure containing data and instructions for working with the data.
To make a new string, you can make a variable and give it a value of new String().
var foo = new String();But, most developers skip that part and use a string literal:
var foo = "my string";concat(text)
The concat() function joins two strings.
var foo = "Hello";
var bar = foo.concat(" World!")
alert(bar); // Hello World!length
Returns the length as an integer.
var foo = "Hello!";
alert(foo.length);indexOf
Returns the first occurrence of a string inside of itself, starting with 0. If the search string cannot be found, -1 is returned. The indexOf() method is case sensitive.
var foo = "Hello, World! How do you do?";
alert(foo.indexOf(' ')); // 6
var hello = "Hello world, welcome to the universe.";
alert(hello.indexOf("welcome")); // 13lastIndexOf
Returns the last occurrence of a string inside of itself, starting with index 0.. If the search string cannot be found, -1 is returned.
var foo = "Hello, World! How do you do?";
alert(foo.lastIndexOf(' ')); // 24replace(text, newtext)
The replace() function returns a string with content replaced. Only the first occurrence is replaced.
var foo = "foo bar foo bar foo";
var newString = foo.replace("bar", "NEW!")
alert(foo); // foo bar foo bar foo
alert(newString); // foo NEW! foo bar fooslice(start[, end])
Slice extracts characters from the start position.
"hello".slice(1); // "ello"
// When the end is provided, they are extracted up to, but not including the end position.
"hello".slice(1, 3); // "el"
// Slice allows you to extract text referenced from the end of the string by using negative indexing.
"hello".slice(-4, -2); // "el"
// Unlike substring, the slice method never swaps the start and end positions. If the start is after the end, slice will attempt to extract the content as presented, but will most likely provide unexpected results.
"hello".slice(3, 1); // ""substr(start[, number of characters]
substr extracts characters from the start position, essentially the same as slice.
"hello".substr(1); // "ello"
// When the number of characters is provided, they are extracted by count.
"hello".substr(1, 3); // "ell"substring(start[, end])
substring extracts characters from the start position.
"hello".substring(1); // "ello"
// When the end is provided, they are extracted up to, but not including the end position.
"hello".substring(1, 3); // "el"
// substring always works from left to right. If the start position is larger than the end position, substring will swap the values; although sometimes useful, this is not always what you want; different behavior is provided by slice.
"hello".substring(3, 1); // "el"toLowerCase()
This function returns the current string in lower case.
var foo = "Hello!";
alert(foo.toLowerCase()); // hello!toUpperCase()
This function returns the current string in upper case.
var foo = "Hello!";
alert(foo.toUpperCase()); // HELLO!trim()
This function removes leading and trailing white spaces from the current string.
var foo = " This line has unnecessary spaces. ";
alert(foo.trim()); // This line has unnecessary spaces.charAt(index)
This function returns the character at a given index of the current string.
var foo = "Bangladesh";
alert(foo.charAt(3)); // gparseInt(string[, radix])
This function parses a numercial string to integer.
If the radix is specified it parses in the specified numeral system.
Radix can be any integer between 2 and 36.
var foo = "23";
alert(parseInt(foo)); // 23
var foo = "1001";
alert(parseInt(foo,2)); // 9parseFloat(string)
This function parses a numercial string to float.
var foo = "10.589";
alert(parseFloat(foo)); // 10.589
var foo = "10";
alert(parseFloat(foo)); // 10Some ES6 workaround
// Template Literals or interpolation
let firstName = "Nuhil";
let lastName = "Mehdy";
console.log(`${firstName} ${lastName}`);let country = "Bangladesh";
console.log(country.repeat(3));
console.log(country.startsWith("Bangla"));
console.log(country.endsWith("desh"));
console.log(country.includes("de"));
/*
BangladeshBangladeshBangladesh
true
true
true
*/// Multiline string
let country = `We
Love
Bangladesh`;
console.log(country);
/*
We
Love
Bangladesh
*/A complex type is an object, be it either standard or custom made. Its home is the heap and goes everywhere by reference (e.g. Array, Object). The common way to declare objects is by using the curly braces:
let myObj = { world: "Earth" };
// Or by
// let myObj = new Object({ world: "Earth" });Objects are compared by reference. That being said, we have this:
let firstObj = {};
let secondObj = {};
// Check if they are equal
firstObj === secondObj
// => false
// Comparing an object with itself...
firstObj === firstObj
// => true
// Let's point the secondObj to firstObj
secondObj = firstObj
// Now they are equal
firstObj === secondObj
// => trueAttention: you have no guarantee that adding the object keys in a specific order will get them in the same order.
var site = new Object(); // Required to not cause error in Internet Explorer
site = {};
site.test = function(string) {
alert("Hello World! " + string);
site.string = string;
}
site.test("Boo!");
alert(site.string);for in is perfect for iterating through an object.
const gimli = {
name: "Gimli",
race: "dwarf",
weapon: "battle axe",
};
// Iterate through properties of gimli
for (let key in gimli) {
console.log(gimli[key]);
}
/*
Gimli
dwarf
battle axe
*/// Initialize method on gimli object to return property keys
Object.keys(gimli);
// => ["name", "race", "weapon"]