Javascript Short Notes -beginner
Javascript Short Notes -beginner
3. Comparison Operators
- `==` : equal to
- `!=` : not equal
- `===` : equal value and type
- `!==` : not equal value or not equal type
- `>` : greater than
- `<` : less than
Chapter 2 - Expressions & - `>=` : greater than or equal to
Conditionals - `<=` : less than or equal to
- `?` : ternary operator
A fragment of code that produces a value is called
an expression. Every value written literally is an
expression. For example, 77 or "Harry."
4. Logical Operators
- `&&` : logical and
Operators in JavaScript
- `||` : logical or
- `!` : logical not
1. Arithmetic Operators
- + : Addition
Apart from these, we also have type and bitwise
- - : Subtraction operators. Bitwise operators perform bit by bit
operations on numbers.
- : Multiplication
Example:
- \\ : Exponentiation
7 + 8 = 15
- / : Division
- % : Modulus
Comments in JavaScript
- ++ : Increment
Sometimes we want our programs to contain text
- -- : Decrement
which is not executed by the JS Engine.
2. Assignment Operators
Conditional Statements
-=:x=y
if-else if statement
Sometimes we might have to execute a block of
code based off some condition.
Sometimes we might want to keep checking a set
For example, a prompt might ask for the age of the of conditions one by one until one matches. We use
user and if it's greater than 18, display a special `if-else if` for achieving this.
message!
if-else statement
Example:
The `if` statement can have an optional `else`
clause. The syntax looks like this:
(marks > 10) ? "yes" : "no"
if (condition) {
// block of code if condition true If marks are greater than 10, you pass; otherwise,
you do not.
} else {
// block of code if condition false
}
If the condition is `true`, the code inside the `if`
block is executed; otherwise, the code inside the
`else` block is executed.
// code to be executed
}
- for loop -> loops a block of code n number of Note: For-in loop also works with arrays which will
times be discussed in later videos.
Note: If the condition never becomes false, the loop Function with parameters
will never end, and this might crash the runtime.
Quick Quiz: Write a sample program demonstrating Another way to create & use the function:
do-while loop
function myFunc() {
// code
Chapter 4 - Strings
let name = 'Adam D'Angelo'
Strings are used to store and manipulate text.
Strings can be created using the following syntax:
We can use a single quote escape sequence to
solve the problem:
let name = "Harry" -> Creates a string
name.length let name = 'Adam D\'Angelo'
-> This property prints length of the string
let a = `This is ${name}` -> Prints This is Harry name.toLowerCase() → prints harry
Accessing values
let numbers = [1, 2, 7, 9] 2. join() → Joins all the array elements using a
separator
numbers[0] = 1
let n = [7, 9, 13]
numbers[1] = 2
n.join(" - ") → "7-9-13"
const n = [1, 7, 9]
6. unshift() → Adds an element to the beginning.
typeof n → returns "object"
Returns new array length
let a = [7, 9, 8]
a.sort() 1. forEach loop -> Calls a function once for each
array element.
Array.from("Harry");
</script>
confirm: Shows a message and waits for the user
to press OK or Cancel. Returns `true` for OK and
Or html `false` for Cancel.
The exact location & look is determined by the
browser, which is a limitation.
Window
|-- DOM
|-- BOM
|-- JavaScript Core
<body>
</body> Note: childNodes looks like an array. But it is not
actually an array but a collection. We can use
</html> Array.from(Collection) to convert it into an Array.
Array methods won't work.
`document.head` -> more children -> Page HTML - They are read-only
tag - They are live: `.childNodes` variable (reference)
Note: document.body can sometimes be null if the will automatically update if childNodes of elem is
JavaScript is written before the body tag. changed.
- They are iterable using `for...of` loop Table links
Siblings and the parent Certain DOM elements may provide additional
properties specific to their type for convenience.
Siblings are nodes that are children of the same
Table element supports the following properties:
parent.
→ document.getElementsByTagName
Returns elements with the given tag name.
→ document.getElementsByClassName
Returns elements that have the given CSS class.
→ document.getElementsByName
Searches elements by the name attribute.
Chapter 8 - Events & other <script>
The output:
Here are some more insertion methods:
<p> Hello </p>
<div id="div"></div>
1. node.append(e) -> append at the end of node
<p> Bye </p>
2. node.prepend(e) -> insert at the beginning of
node
Node removal
3. node.before(e) -> insert before node
4. node.after(e) -> insert after node
To remove a node, there's a method node.remove()
5. node.replaceWith(e) -> replaces node with the
given node
let id1 = document.getElementById("id1")
Quick Quiz: Try out all these methods with your
own webpage.
id1.remove()
Example:
3. elem.classList.contains("class") - Checks for the An event is a signal that something has happened.
given class, returns true/false All the DOM nodes generate such signals.
SetTimeout allows us to run a function once after Mouse events: click, contextmenu (right click),
the interval of time. mouseover, mouseout, mousedown/mouseup,
mousemove
Syntax of setTimeout is as follows:
let timerId = setTimeout(() => alert("never"), 1000); <input value = "Hey" onclick = "alert('Hey')" type =
"button">
Browser Events
addEventListener is used to assign multiple
handlers to an event.
element.addEventListener(event, handler)
element.removeEventListener(event, handler)
}
The syntax of a Promise looks like this:
Now we can do something like this: let promise = new Promise (function (resolve,
reject) {
// executor
loadScript('https://cdn.harry.com', (script) => {
});
alert('Script is loaded');
alert(script.src);
resolve and reject are two callbacks provided by
}); JavaScript itself. They are called like this:
resolve (value) -> If the job is finished successfully
Pyramid of Doom reject (error) -> If the job fails
When we have callback inside callbacks, the code The promise object returned by the new Promise
gets difficult to manage: constructor has these properties:
1. state: Initially pending then changes to either Promises Chaining
"fulfilled" when resolve is called or "rejected" when
We can chain promises and make them pass the
reject is called
resolved values to one another like this:
promise.then (alert);
Attaching multiple handlers
promise.catch (alert);
let p is a promise
1. Promise.all(promises) -> Waits for all promises An async function always returns a promise. Other
to resolve and returns the array of their results. If values are wrapped in a promise automatically.
any one fails, it becomes the error & all other
results are ignored.
We can do something like this:
Async/Await
We all make mistakes. Also sometimes our script
can have errors. Usually a program halts when an
There is a special syntax to work with promises in error occurs.
Javascript
Setting Prototype
Class myClass {
Constructor (){}
We can set prototype by setting __proto__. Now if
we read a property from the object which is not in }
the object and is present in the prototype,
JavaScript will take it from the prototype.
Class Inheritance
If we have a method in the object it will be called Class inheritance is a way for one class to extend
from the object. If it's missing in the object and another class. This is done by using the extends
present in the prototype, it's called from the keyword.
prototype.
The Extends keyword
run() {
The extends keyword is used to extend another super.run()
class.
this.hide()
}
Class Lion extends Animal {}
Overriding Constructor
Class Child extends Parent
With a constructor, things are a bit tricky/different.
According to the specifications, if a class extends
another class and has no constructor, then the
We can create a class Monkey that inherits from
following empty constructor is generated.
Animal
Class Employee {
Super(a, b) -> call parent constructor
static sMethod() {
alert("Hey");
}
}
Employee.sMethod();
Example:
Class Person {
get (name) {
return this._name;
}
set name(newName) {
this._name = newName;
}
}
instanceof Operator
The instanceof operator allows to check whether an
object belongs to a certain class.
With let and var hoisting is different Exercise 2 - Snake Water Gun
console.log(num) => Error if let or const Use JavaScript to create a game of Snake Water &
let num = 6; => With var undefined is printed Gun. The game should ask you to enter S, W or G.
The computer should be able to randomly generate
Function expressions and class expressions are not S, W or G and declare win or loss using alert. Use
hoisted. confirm and prompt wherever required.
Exercise 5 - Hackermon
Write a JavaScript program to pretend to look like a
hacker. Write an async function which will simply
display the following output: