Set of JavaScript basic syntax to add, execute and write basic programming paradigms in Javascript
Adding internal JavaScript to HTML
<script type="text/javascript"> /*JS code goes here*/ </script>
Adding external JavaScript to HTML
<script src="filename.js"></script>
JavaScript Function syntax
function nameOfFunction() {
// function body
}
Changing content of a DOM Element
document.getElementById("elementID").innerHTML = "Hello World!";
This will print the value of a in JavaScript console
console.log(a);
Conditional statements are used to perform operations based on some conditions.
The block of code to be executed, when the condition specified is true.
if (condition) {
// block of code to be executed if the condition is true
}
If the condition for the if block is false, then the else block will be executed.
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
A basic if-else ladder
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Switch case statement in JavaScript
switch (expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Iterative statements facilitate a programmer to execute any block of code lines repeatedly and can be controlled as per conditions added by the programmer.
For loop syntax in JavaScript:
for (initialization; condition; incrementation;) {
// code block to be executed
}
Example:
for (let i = 0; i < 5; i++) {
text += "Iteration number: " + i + "<br>";
}
Use for...in when you need to iterate through the keys of an object and access their values.
let student = {
name: 'John Doe',
age: 20,
course: 'Computer Science'
};
for (let key in student) {
console.log(key + ': ' + student[key]);
console.log(student[key]); //or
}
or you can use it for Arrays also. But its better to use FOR OF loop for Array
// Looping over an array
const fruits = ["apple", "banana", "orange"];
for (const fruit in fruits) {
console.log(fruits[fruit]);
}
// Looping over a string
const message = "Hello world!";
for (const char in message) {
console.log(message[char]);
}
Use for...of when you need to iterate through the values of an iterable object in order.
const fruits = ["apple", "banana", "orange"];
for (const fruit of fruits) {
console.log(fruit); // This will print each fruit individually
}
// Another way to achieve the same result:
for (const fruit of "apple,banana,orange".split(",")) {
console.log(fruit);
}
Runs the code until the specified condition is true.
while (condition) {
// code block to be executed
}
Example
let number = 10;
while (number > 0) {
console.log(number);
number--;
}
A do while loop is executed at least once despite the condition being true or false.
do {
// run this code in block
i++;
} while (condition);
Example
let count = 0;
do {
console.log("Iteration " + count);
count++;
} while (count < 5);
The string is a sequence of characters that is used for storing and managing text data.
Returns the character from the specified index.
str.charAt(3);
Joins two or more strings together.
str1.concat(str2);
Returns the index of the first occurrence of the specified character from the string else -1 if not found.
str.indexOf('substr');
Searches a string for a match against a regular expression.
str.match(/(chapter \d+(\.\d)*)/i;)
Searches a string for a match against a specified string or char and returns a new string by replacing the specified values.
str1.replace(str2);
Searches a string against a specified value.
str.search('term');
Splits a string into an array consisting of substrings.
str.split('\n');
Returns a substring of a string containing characters from the specified indices.
str.substring(0,5);
The array is a collection of data items of the same type. In simple terms, it is a variable that contains multiple values.
Containers for storing data.
var fruit = ["element1", "element2", "element3"];
Joins two or more arrays together.
concat()
Returns the index of the specified item from the array.
indexOf()
Converts the array elements to a string.
join()
Deletes the last element of the array.
pop()
This method reverses the order of the array elements.
reverse()
Sorts the array elements in a specified manner.
sort()
Converts the array elements to a string.
toString()
Returns the relevant Number Object holding the value of the argument passed.
valueOf()
Rounds a number upwards to the nearest integer and returns the result.
ceil(x)
Returns the value of E^x.
exp(x)
Returns the logarithmic value of x.
log(x)
Returns the value of x to the power y.
pow(x, y)
Returns a random number between 0 and 1.
random()
Returns the square root of a number x.
sqrt(x)
Date object is used to get the year, month, and day. It has methods to get and set day, month, year, hour, minute, and seconds.
Returns the date from the date object.
getDate()
Returns the day from the date object.
getDay()
Returns the hours from the date object.
getHours()
Returns the minutes from the date object.
getMinutes()
Returns the seconds from the date object.
getSeconds()
Returns the time from the date object.
getTime()
Any change in the state of an object is referred to as an Event. With the help of JS, you can handle events, i.e., how any specific HTML tag will work when the user does something.
Fired when an element is clicked.
element.addEventListener('click', () => {
// Code to be executed when the event is fired
});
Fired when an element is right-clicked.
element.addEventListener('contextmenu', () => {
// Code to be executed when the event is fired
});
Fired when an element is double-clicked.
element.addEventListener('dblclick', () => {
// Code to be executed when the event is fired
});
Fired when an element is entered by the mouse arrow.
element.addEventListener('mouseenter', () => {
// Code to be executed when the event is fired
});
Fired when an element is exited by the mouse arrow.
element.addEventListener('mouseleave', () => {
// Code to be executed when the event is fired
});
Fired when the mouse is moved inside the element.
element.addEventListener('mousemove', () => {
// Code to be executed when the event is fired
});
Keyboard events are fired when a user interacts with the keyboard. You can use JavaScript to handle these events, such as detecting when a key is pressed, when a key is released, or when a key is held down.
Fired when the user is pressing a key on the keyboard.
element.addEventListener('keydown', () => {
// Code to be executed when the event is fired
});
Fired when the user presses a key on the keyboard.
element.addEventListener('keypress', () => {
// Code to be executed when the event is fired
});
Fired when the user releases a key on the keyboard.
element.addEventListener('keyup', () => {
// Code to be executed when the event is fired
});
Errors are thrown by the compiler or interpreter whenever they find any fault in the code, and it can be of any type like syntax error, run-time error, logical error, etc. JavaScript provides some functions to handle the errors.
Try the code block and execute catch when an error is thrown.
try {
// Block of code to try
} catch (err) {
// Block of code to handle errors
}
Methods that are available from the window object.
Used to alert something on the screen.
alert();
The blur() method removes focus from the current window.
blur();
Keeps executing code at a certain interval.
setInterval(() => {
// Code to be executed
}, 1000);
Executes the code after a certain interval of time.
setTimeout(() => {
// Code to be executed
}, 1000);
The Window. close() method closes the current window.
window.close();
The window.confirm() instructs the browser to display a dialog with an optional message and to wait until the user either confirms or cancels.
window.confirm('Are you sure?');
Opens a new window.
window.open("https://www.chandan-p-006.netlify.com");
Prompts the user with a text and takes a value. The second parameter is the default value.
var name = prompt("What is your name?", "Harry");
window.scrollBy(100, 0); // Scroll 100px to the right
window.scrollBy(100, 0);
Scrolls the document to the specified coordinates.
window.scrollTo(500, 0); // Scroll to horizontal position 500
Clears the setInterval. The variable is the value returned by setInterval call.
clearInterval(var);
Clears the setTimeout. The variable is the value returned by setTimeout call.
clearTimeout(var);
Stops further resource loading.
stop();
The browser creates a DOM (Document Object Model) whenever a web page is loaded, and with the help of HTML DOM, one can access and modify all the elements of the HTML document.
Selector to select the first matching element.
document.querySelector('css-selectors');
A selector to select all matching elements.
document.querySelectorAll('css-selectors', ...);
Select elements by tag name.
document.getElementsByTagName('element-name');
Select elements by class name.
document.getElementsByClassName('class-name');
Select an element by its id.
document.getElementById('id');
Create new elements in the DOM.
Create a new element.
document.createElement('div');
Create a new text node.
document.createTextNode('some text here');