What is JavaScript?
JavaScript is a programming language that is commonly used to add interactivity and other dynamic features to websites. It can run on the front-end (client-side) or back-end (server-side) of a website, and it allows you to create things like:
- Interactive forms and quizzes
- Image sliders and galleries
- Pop-up windows and dialog boxes
- Interactive maps
- Dynamic content that can update in real-time, without the need to refresh the page
- Games and other interactive applications
JavaScript code can be written directly into HTML documents, or it can be linked to separate JavaScript files that are included in the HTML. When a browser loads an HTML document, it runs any JavaScript code it finds, which can manipulate the HTML and CSS to create dynamic effects on the page.
It's important to note that JavaScript is a different language than Java. Although they share some similarities in their syntax, they are used for different purposes and they have many differences in terms of their capabilities and their use cases.
Understanding Let and Const
In JavaScript, let
and const
are both used to declare variables, but they have some differences:
let
is used to declare variables that are meant to be re-assigned later. It is a block-scoped variable, which means it is only accessible within the block it was declared, as well as in any blocks nested within it.const
is used to declare variables that are meant to be read-only, meaning their values cannot be reassigned. Likelet
,const
is also block-scoped.
Here's an example of how you might use let
and const
in JavaScript:
const num = 42; // Declare a read-only variable
num = 50; // This will throw an error, because num is a constant
let message = "Hello, world!"; // Declare a variable that can be reassigned
message = "Hi, there!"; // This is okay, because message is a let variable
if (num === 42) {
let num = 50; // Declare a new block-scoped variable
console.log(num); // 50
}
console.log(num); // 42
Note that you cannot use let
or const
to declare variables with the same name within the same block. This will result in a SyntaxError
.
Arrow function:
Arrow functions are a syntax for writing functions in JavaScript. They are a more concise way to write functions that are anonymous or functions that are not bound to an identifier. Arrow functions are also known as "fat arrow" functions because of the "fat" arrow notation (=>) used to define them.
Here's an example of an arrow function that takes two arguments, x
and y
, and returns the sum of those two arguments:
const add = (x, y) => x + y;
This is equivalent to the following function expression:
const add = function(x, y) {
return x + y;
};
Arrow functions are often used in place of anonymous functions, especially when the function is short and simple. They can make your code more concise and easier to read.
Export and Import function:
In JavaScript, the export
and import
statements are used to include code from one JavaScript file into another.
Here is an example of how to use the export
statement to export a function from a file called math.js
:
// math.js
export function add(a, b) {
return a + b;
}
To include this code in another file, you can use the import
statement in the following way:
// app.js
import { add } from './math.js';
console.log(add(1, 2)); // 3
You can also use the export
statement to export multiple values or objects, like this:
// math.js
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
Then you can import them all at once like this:
// app.js
import * as math from './math.js';
console.log(math.add(1, 2)); // 3
console.log(math.subtract(1, 2)); // -1
You can also use the export
statement to export a value or object by default, like this:
// math.js
const add = (a, b) => a + b;
export default add;
Then you can import it like this:
// app.js
import add from './math.js';
console.log(add(1, 2)); //
Classes and MethodsJavaScript, a class is a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or properties), and implementations of behavior (member functions or methods). Classes in JavaScript are "syntactical sugar" for JavaScript's existing prototype-based inheritance.Here's an example of a basic class definition for a simple "Person" class:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
In this example, the constructor
method is a special method that is called when a new instance of the class is created. It's used to initialize the object's properties. The sayHello
method is a regular method that can be called on an instance of the class.
Here's an example of how you might use this class to create a new object:
const john = new Person("John Doe", 30);
john.sayHello(); // Outputs: "Hello, my name is John Doe and I am 30 years old."
JavaScript also support the static
keyword to define static methods that can be called on the class itself, rather than on an instance of the class.
For example:
class Person {
static staticMethod() {
console.log('I am a static method');
}
}
Person.staticMethod();
JavaScript also support the extends and super keyword for inheritance, you can use the extends
keyword in a class definition to create a subclass and the super
keyword to call the parent class's constructor method and methods .
class Student extends Person {
constructor(name, age, major) {
super(name, age);
this.major = major;
}
}
I hope this gives you a good idea of how classes and methods work in JavaScript. Let me know if you have any more question.In JavaScript, a method is a property of an object that is a function. It is used to perform a specific action on or with the data of an object.
Here's an example of a simple object with a method:
let person = {
name: "John Doe",
age: 30,
greet: function() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
};
person.greet(); // Output: "Hello, my name is John Doe and I am 30 years old."
In the example above, the greet
method is a function that is a property of the person
object. It uses the this
keyword to access the data (name
and age
) of the object and output a message. The greet
method is called by appending parentheses ()
to the method name like a function call.
JavaScript also has several built-in objects, such as the Array
and String
objects, that come with their own methods. For example, here is how you can use the toUpperCase()
method of the String
object to convert a string to uppercase:
let message = "hello world";
console.log(message.toUpperCase()); // Output: "HELLO WORLD"
Another example of this is the Array Object, forEach()
method which can be used to iterate over the elements of an array:
let colors = ['red', 'green', 'blue'];
colors.forEach(color => console.log(color));
// Output: red green blue
ES6 introduce the arrow function
which is the shorthand of anonymous function, and also the Object.entries()
, Object.keys()
, Object.values()
method which can be used to get all the key-value pairs of an object
let car = {
brand: "Toyota",
model: "Camry",
year: 2020
};
console.log(Object.entries(car));
// Output: [ [ 'brand', 'Toyota' ], [ 'model', 'Camry' ], [ 'year', 2020 ] ]
You can find the JavaScript reference document for the built-in objects and their methods on the Mozilla Developer Network (MDN) website.
Spread and Rest Operator:
In JavaScript, the spread operator (written as "...") and the rest operator (also written as "...") are used to expand and gather arrays, respectively.
The spread operator is used to expand an array into its individual elements, and can be used in a variety of ways. For example, you can use the spread operator to merge two arrays together:
let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
let mergedArray = [...array1, ...array2];
console.log(mergedArray); // [1, 2, 3, 4, 5, 6]
You can also use it to copy an array:
let originalArray = [1, 2, 3];
let copiedArray = [...originalArray];
console.log(copiedArray); // [1, 2, 3]
The rest operator, on the other hand, is used to gather multiple elements into an array. It is often used in function arguments to represent an indefinite number of arguments.
function example(first, second, ...remaining) {
console.log(first); // 1
console.log(second); // 2
console.log(remaining); // [3,4,5]
}
example(1, 2, 3, 4, 5);
You could also use Rest operator with destructuring to grab the remainig elements of an array
let [a, b, ...c] = [1, 2, 3, 4, 5];
console.log(a); // 1
console.log(b); // 2
console.log(c); // [3, 4, 5]
It's important to note that you can use the rest operator only once in a single function argument list, because the rest parameter must be the last one.
Destructing in Javascript
In JavaScript, destructuring is a feature that allows you to extract values from arrays or objects and assign them to variables. This can be done using the destructuring assignment syntax, which looks like this:
let array = [1, 2, 3];
let [a, b, c] = array;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
let obj = {x: 1, y: 2, z: 3};
let {x, y, z} = obj;
console.log(x); // 1
console.log(y); // 2
console.log(z); // 3
In the example above, the values of the array
and obj
are being destructured and assigned to variables a,b,c
and x,y,z
respectively.
This is useful in cases where you want to extract a few values from a larger data structure and use them independently, rather than having to access the values through the larger data structure every time you want to use them.
Reference and primitive types:
In JavaScript, variables can hold primitive values (e.g. numbers, strings, booleans) or references to objects. Primitive values are stored in the variable itself, whereas objects are stored in memory and the variable holds a reference to that location in memory.
For example:
let x = 5; // x holds the primitive value 5
let y = "hello"; // y holds the primitive value "hello"
let z = x; // z holds a copy of the value in x (5)
x = 6; // x now holds the value 6, but z still holds 5
let obj1 = { a: 1 }; // obj1 holds a reference to an object { a: 1 }
let obj2 = obj1; // obj2 also holds a reference to the same object
obj1.a = 2; // the object's value changes, so obj2.a is now also 2
It is important to understand the difference between primitive and reference types because it affects how they are passed to functions and how they are compared.
For example, when passing primitive types to a function as an argument, a copy of the value is passed and any changes made to the argument within the function will not affect the original variable.
When passing reference types, the reference is passed to the function, and any changes made to the object within the function will be reflected in the original variable because both references point to the same object in memory.
Also, when comparing primitive types, their values are compared, whereas when comparing references, their memory addresses are compared.
For example:
let x = 5;
let y = 5;
console.log(x == y); // true
let obj1 = { a: 1 };
let obj2 = { a: 1 };
console.log(obj1 == obj2); // false
console.log(obj1 === obj2); // false
No comments:
Post a Comment