JS Guides

Welcome to JS Guides, a small document containing the fundamentals of JavaScript that are MUST KNOWS when developing with JavaScript.

JavaScript is like any other coding language when it comes to logic. The thing that stands out with JavaScript, however, is how universal it can be. It has many elements that can be used for front-end web development, app development, server stacks and even game engines.

Fundamentals
Selectors
Event listeners
Functions
Loops
ES6

Variables

A JS variable is a container for a value. It can hold any type of information that can then be used later on in the script.
When you first use a JS variable, you need to declare it by saying var followed by the the variable name.
There are a few rules when creating a JS variable.
It:

  • cannot contain spaces
  • cannot just be a number
  • must begin with a letter, an underscore or a dollar sign
  • is case-sensitive
  • must not be a reserved word - Reserved Words
  • should ideally have a name that describes whatever the variable is holding.


							
								// Number
								var variableNumber = 1;
								// String
								var variableString = "This is a string";
								// Array
								var variableArray = ["Item 1", 2, false, "Item 4"];
	                    	
						

Variables can also hold more complex information like objects and even HTML elements.

							
								// Object
								var variableObject = {
									"location": "2 Bunny St, Pipitea, Wellington",
									"course": "Web anx UX Design",
									"students": 11
								};
								// HTML element
								var variableArray = document.getElementById('contentBox');
	                    	
						

Variable States

Variables at their core have two states, true and false.
These are determined by the contents of the variable. If the variable contains a value, it is considered true. So if the variable is empty, undefined, null, false or 0, it is then considered false.

							
								var test1; // false
								var test2 = 0; // false
								var test3 = "string"; // true
								var test4 = 1; // true
								var test5 = null; // false
								var test6 = true; // true
								var test7 = false; // false
							
						

These states are only used in variable checking based operations and CANNOT be used as individual values.

							
								// This won't trigger, because test1 has a false state
								if (test1) {
									console.log('Cool!');
								}

								// This will trigger, because test4 has a true state
								if (test4) {
									console.log('Cool!');
								}
							
						

If and Else Statements

If statements are a way to introduce logic into your code.
At their core, they are checking to see if the condition is true or false. True will trigger the code inside it, and false will skip it. Unless it has an else statement, in which case it will then run the code inside the else statement.

							
								if (test4 == 1) {
									console.log("test4 is equal to 1");
								}
								// This will only run if test4 is equal to 1

								if (test4 == 1) {
									var variableNumber = 2;
								} else {
									var variableNumber = 6;
								}
								// if test4 is equal to 1, variableNumber will then be equal to 2
								// However, this time if test4 does not equal 1, variableNumber will be set to 6
								hr
							
						

Conditions

Conditions are checks that return true or false. They are used to check if the values on either side of them match their condition.
They are mainly used in if statements, as they do not need to be set to a variable to return a value.

							
								==  // Checks if the 2 values have the same value
								=== // Checks if the 2 values have the same value AND the same data type
								<   // Checks if the value on the left is less than the value on the right
								<=  // Checks if the value on the left is less than or equal to the value on the right
								>   // Checks if the value on the left is greater than the value on the right
								>=  // Checks if the value on the left is greater than or equal to the value on the right
								!=  // Checks if the 2 values DO NOT equal each other
								!== // Checks if the 2 values DO NOT equal each other AND are not the same data type
							
						

Multi-Layer Conditions

Multi-layer conditions allow you to have multiple conditions inside the same condition.
This allows for more advanced checks to happen within a single condition, because more variables can be used.
These are nestable, so an infinite amount can be used within a 'single' condition.

							
								&& // Allows the use of 2 different conditions within the same condition
								|| // Checks if either of the two conditions is true; if at least one of them is, continue.

								// This won't trigger the console log, because the second condition has returned false.
								if (("thing" == "thing") && (1 == 2)) {
									console.log('Cool!');
								}

								// This will trigger the console log, because it is only looking for one of the conditions to be true.
								if (("thing" == "thing") || (1 == 2)) {
									console.log('Cool!');
								}
							
						

Operators

Operators are used to manipulate values.
They can be used to manipulate variables, or just raw data. Like adding two strings together in a console log, for example.

							
								= // Sets the variable on the left to a new value on the right
								+ // Adds the 2 values on each side to each other
								- // Subtracts 2 NUMBER values from each other
								/ // Divides 2 NUMBER values from each other
								* // Multiplies 2 NUMBER values by each other
								% // Gives the remainder value when given 2 NUMBERS
								! // Sets the output of the result to the opposite. ONLY USED on true / false results
							
						

Get Element By Id

The getElementById function does exactly what it says in the title. It gets an HTML element by the id that is passed as a parameter.
Notice how you don't need to include a # in the parameters. That is because the function is already looking for an ID and nothing else.
This will only return a single HTML element to then be used or stored in a variable.


							
								// Selecting the element
								document.getElementById('element');
								// Storing the element
								var elementId = document.getElementById('element');
							
						

Get Elements By Class Name

Like getElementById, the getElementsByClassName function does exactly what it says in the title. It gets all the elements it can find with the passed class name.
Also like getElementById, it is only looking at the class names. So you don't have to put a full stop (.) in the parameters.
So while getElementById returns a single HTML element, getElementsByClassName will return an array of elements. Even it it only finds 1 element, it will still be stored in an array format.
This means that to access the elements in your JS code, you have to loop through the array given to you to select one of the individual elements.


							
								// Selecting the elements
								document.getElementsByClassName('element');
								// Storing the element
								var elementClass = document.getElementsByClassName('element');
								// Getting the HTML elements to use
								for (var i = 0; i < elementClass.length; i++;) {
									// Now we can use this variable for any edits we want to make to the element
									var currentElement = elementClass[i];
								}
							
						

Query Selector

The querySelector function is a little different from the other two functions. It can select elements from both id and class. However it can also be used for some more advanced selections of any HTML attributes, including HTML tags themselves.
Unlike getElementsByClassName, querySelector will always return the first element that matches its parameters. So if you try to select an element by its class name, and there are three elements with the same class name, then it will always return the first one that appears in the HTML code.
The catch with using querySelector is that it doesn't know what to look for at first. So you have to tell it what type you are trying to select. It basically runs off the same type of selecting process as CSS. So a class query will start with a full stop (.) and an id query will start with a hashtag (#).


							
								// Selecting an id element
								var queryElementId = document.querySelector('#element');
								// Selecting a class element
								var queryElementClass = document.querySelector('.element');
								// Selecting a HTML tag element
								var queryElementClass = document.querySelector('h3');
								// Selecting an image element with a certain src
								var queryElementImgSrc = document.querySelector('img[src="image/test.png"]');
							
						

querySelector is very powerful. Basically any type of selection you can do in CSS will work for querySelector.


							
								// Select anchor element with a certain href
								var queryElementAHref = document.querySelector('a[href="page.html"]');
								// Select header class with a certain data attribute
								var queryElementClassData = document.querySelector('.header[data-number="3"]');
							
						

Query Selector All

The querySelectorAll function takes all of the advanced selection features of querySelector, and combines it with the return array feature of getElementsByClassName.
This can be very useful if you need to select multiple regular HTML elements (like images that don't all have the same class) and process all of them at the same time.
Or for example you have a class that changes the colour of some text, but you only want to select all h3 elements with this class and none of the other elements that have the red class.

							
								// Select all span elements on the page
								var queryElementH2 = document.querySelectorAll('span');
								// Select all h3 elements on the page
								var queryElementH2 = document.querySelectorAll('h3.red');
								// Getting the HTML elements to use
								for (var i = 0; i < queryElementH2.length; i++;) {
									// Now we can use this variable for any edits we want to make to the element
									var currentElement = queryElementH2[i];
								}
							
						

Add Event Listener

The addEventListener function allows you to add a custom event to an element. These events will trigger based off the first parameter given, and call the second parameter which can be a named function or an anonymous function.
There are a lot of different event types that do different things. The list of them all can be found here https://www.w3schools.com/jsref/dom_obj_event.asp


							
								// Select an HTML element
								var element = document.getElementById('content');
								// Add an event listener structure
								element.addEventListener(eventType, function);
							
						

When assigning a function to the addEventListener, there are two ways to go about it: adding a named function or adding an anonymous function.
When adding a named function, instead of normally adding in the function name and then the brackets, you only need to add the function name. This is because if you add in the brackets, the function will be called even if the event doesn't trigger.
The other way is to add an anonymous function. This will allow you to run some code directly inside the event listener. This is also the way that you would use if you needed to pass some parameters through a function.


							
								// Custom function
								function test () {
									console.log('This is a console log inside a function');
								}
								// Select an HTML element
								var element = document.getElementById('content');
								// Add an event listener to run the function
								element.addEventListener('click', test);


								// Another custom function
								function test2 (message) {
									console.log(message);
								}
								// Select an HTML element
								var element2 = document.getElementById('content');
								// Add an event listener to run the function
								element.addEventListener('click', function(){
									test2('This is an anonymous function that is sending information to the test2 function')
								});
							
						

Click

The click event will trigger whenever the element is clicked. This can be a button, a span or even a div. However, even though that event may be clickable, it does not change the mouse cursor to the pointer.


							
								// Add a click event listener
								element.addEventListener('click', functionName);
							
						

Input

The input event will trigger whenever an input element has user input. This event is only useful for all the input types and the textarea HTML elements.


							
								// Add an input event listener
								element.addEventListener('input', functionName);
							
						

Change

The change event is very similar to the input type. However, instead of triggering the event when the value is changed, it gets triggered when the value is finished being changed (or when the element loses focus)


							
								// Add a change event listener
								element.addEventListener('change', functionName);
							
						

Function Structure

Functions are the main building blocks of almost any coding language. They all pretty much have the same format. Also, they:

  • can be named or anonymous
  • can have parameters
  • have their own variable scope
  • can return a value to be used outside of itself


							
								// Function structure
								function namedFunction (variable1, variable2) {
									var newVariable = variable1 + variable2;
									return newVariable;
								}
							
						

Parameters

The parameters of a function act just like normal variables. What is special about them is that they can only be used inside the function they are made in. Also, they need to be present when calling the function or else they will call an error.
When making parameters, you don't need to include the var at the start as you do with a normal variable. Doing this will cause an error.


							
								// Correct
								function namedFunction (variable1, variable2) {
									var newVariable = variable1 + variable2;
									return newVariable;
								}

								// Incorrect
								function namedFunction (var variable1, var variable2) {
									var newVariable = variable1 + variable2;
									return newVariable;
								}
							
						

Return

The return statement allows the function to return a value to the line that called it. It can also be used for stopping a function early.

							
								// Making the function
								function messageFunction (person, message) {
									return "Hello " + person + ". " + message;
								}

								// Storing the function's return value
								var result = messageFunction('James', 'How are you doing?');
								console.log(result);
								// This will output 'Hello James. How are you doing?'
							
						

For Loop Structure

The for loop is the simplest way to make a loop in JavaScript. It can be used for many different things, but the most common is for iterating over an array.
The structure of the for loop is split into 4 parts:

  • The statement
  • The variable
  • The condition
  • What happens after an iteration

All of these parts must be present for the for loop to function.


							
								// Example array
								var arrayName = ['a', 'b', 'c', 'd'];
								// For loop example
								for (var i = 0; i < arrayName.length; i++) {
									console.log(arrayName[i]);
								}
							
						

Break

The break statement is used if you need to stop the loop early. It is recommended to put your break inside an if statement so that your loop doesn't just finish after the first iteration.


							
								// Example array
								var arrayName = ['a', 'b', 'c', 'd'];
								// For loop example
								for (var i = 0; i < arrayName.length; i++) {
									if (arrayName[i] == 'c') {
										console.log('c is in number ' + i + ' of arrayName');
									}
									console.log(arrayName[i]);
								}
							
						

Let and Const

ES6 introduces 2 new variable declaration types, let and const. These variable are jut like normal var variables. They can stoe numbers, strings arrays etc, but they also have some extra functionality.
The let variable is a strict scope variable. And this means for more than just functions. This works for all scope types. Functions, if / else statments, for loops. Basicly if the let variable is in any curly brackets, then it cant go out side of them.


							
								var varVariable = 'This is a var variable';
								let letVariable = 'This is a let variable';

								console.log(varVariable); // This would log 'This is a var variable'
								console.log(letVariable); // This would log 'This is a let variable'


								if (1 == 1) {
									var test = "hello";
								}
								console.log(test); // This will console log 'hello'

								if (1 == 1) {
									let test2 = "hello";
								}
								console.log(test2); // This will throw an error as test2 is scoped inside the if statment


								for (var i = 0; i < 10; i++) {
									console.log('This will log 10 times');
								}
								console.log(i); // This will log 10

								for (let j = 0; j < 10; j++) {
									console.log('This will log 10 times');
								}
								console.log(j); // This will throw an error because j is inside the for loop
							
						

The const variable acts exactly like the let variable in terms of how strick it is with the scope. However the diference with const is that once the variable is set, it can not be changed.
If you do try to change a const variable after it has been set, it will throw an error and not run any more javascript.


							
								const amount = 100;

								if (amount == 100) {
									const anotherAmount = 200;
								}

								console.log(anotherAmount); // This will throw an error because anotherAmount can only be used in the if statment

								amount = 150; // This will also throw an error because amount has already been defined
							
						

Back Tick string concatenation

ES6 also introduces a new way to add variables to strings. This new way is actually the way that most other languages go about adding variables to strings. though the syntax may be different.
To do this, we need to use the back tick (``) to make the string (it is the button on the top left of your keyboard next to the number 1 key). You can then write the string as normal inside the back ticks.
When you need to add a variable, you then need to type ${variableName} inside the string. No need to close the string or add any pluses (+) to join them togeather.


							
								const carBrand = 'Mazda';

								let oldString = 'I saw a blue ' + carBrand + ' today.';

								let newString = `I saw a blue ${carbrand} today.`;
							
						

Arrow Functions

Arrow functions are the new way to make functions in ES6. They can be made as named functions, and anonymous functions.
The main diference with the named arrow function, is that we set it to a const variable. This way we cant accidentally change the variable it is stored in.
Functions are still called the same way.


							
								function oldFunction (pram1) {
									console.log(pram1);
								}

								const newFunction = pram1 => {
									console.log(pram1);
								}

								oldFunction('Hello');
								newFunction('there');

								// If multable parameters are required, just put brackets around them and separate them with commas
								// eg const newFunction = (pram1, pram2, pram3, etc) => {
							
						

Map

A map is a new way to do loops in ES6. What is great about the map, is that it doesnt require you to make an i variable. It just naturlaly knows where abouts in the array it is.
If you do however need the i variable, i can be added as a second argument in the anonymous function.


							
								let numbersArray = [2, 5, 7, 9];

								// Old JavaScript way
								for (var i = 0; i < numbersArray.length; i++;) {
									console.log(numbersArray[i]);
								}

								// New ES6 way
								numbersArray.map((number)=> {
									console.log(number);
								});
							
						

New object features

ES6 also introduces some a new way to reference object variables. Unlike the other ES6 features that have been mentioned so far, this is more of a quality of life improvement and can simply the coding process.


							
								let person = {
									name: 'James',
									age: 20,
									gender: 'male',
									phone: 'iPhone 6s'
								}

								// Old JavaScript way
								let name = person.name;
								let age = person.age;
								let gender = person.gender;
								let phone = person.phone;

								// New ES6 way
								let {name, age, gender, phone} = person;