Bootstrap at a glance

July 28, 2023 Reading time: 10 minutes

What

A free CSS framework to work with when time supply is running low.

Version 3 is the most stable version, supported by all modern browsers.

How

Bootstrap is a combination of pre-written CSS and JavaScript (jQuery) files, both available from a CDN. To access it, add reference to head element:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

Where

Some code snippets are available on my dedicated CodePen

Basic structure

A section needs a container class

Encapsulate your section into a container class which can be either:

  • container (fixed width container) OR
  • container-fluid (full width container)

A section is 12 columns-wide

Group elements in a row with row class then distribute included elements into columns per screen size with col-screenSize-numberOfColumns class. An additionnal well class would add grey background color and rounded border to the zone.

size would be:

  • xs for phones - screens less than 768px wide / extra-small
  • sm for tablets - screens equal to or greater than 768px wide / small
  • md for small laptops - screens equal to or greater than 992px wide / medium
  • lg for laptops and desktops - screens equal to or greater than 1200px wide / large

numberOfColumns is a number between 1 and 12. A row should have a total of 12 colums for each screenSize.

For instance, if we want to align 3 buttons in a row, it means 1 button should be 4 colums wide (3 * 4 = 12).

<div class="row">
<div class="col-xs-4 col-md-4 col-lg-4 well">
  <button>1</button>
 </div>
<div class="col-xs-4 col-md-4 col-lg-4 well">
  <button>2</button>
 </div>
<div class="col-xs-4 col-md-4 col-lg-4 well">
  <button>3</button>
 </div>
</div>

Navbar

Add a static navbar to the top of the page with your website's name, dropdowns, collapsable for small screens, align sign in button to the right and so on. Have a look on CodePen.

Basic classes

Contextual Colors and Backgrounds

Classes for colors are:

  • element-muted
  • element-primary
  • element-success
  • element-info
  • element-warning
  • element-danger

element could be text, bg, alert, btn

Image and image gallery

Some useful class for img element:

  • img-thumbnail: adds some rounded borders and padding
  • img-responsive: applies display: block, max-width: 100% and height: auto.

To create a gallery, combine thumbnail class with Bootstrap grid system:

  • create an element with container class
  • within the container, create as many elements with row class as you need
  • within each row, divide the space into as many colums as you need (col-screenSize-numberOfColumns)
  • within each colum, apply thumbnail class to a wrapper element such as figure that will contain a link to the image source full size that will itself contain
    • the image element
    • a figcaption element

Create an 'alert' element

Show the user some confirmation or alert message within an element, such as a div. Apply alert class to an element in addition with a alert-contextualColor class (see above) and alert-dismissible class to allow user to remove the element. Removal can be smoothened with fade and in classes. For instance:

<div class="alert alert-success alert-dismissible fade in">
  <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
  <strong>Success!</strong> Indicates a successful or positive action.
</div>

Customize button, a, input

Basic classes to apply on a button, a or input elements are:

  • btn and
  • btn-default (display as wide as the text it contains) OR
  • btn-block (as wide as 100% of the available width (breaks on a new line))

Then add if needed:

  • color: btn-contextualColor
  • size: btn-size

a & button groups

A collection of share links can typically be grouped on a single line with btn-group or btn-group-vertical (+ -size if needed) applied on wrapper element.


functions

April 13, 2023 Reading time: 4 minutes

Dividing the code into functions is essential.

Basically, a function can take an input (from zero to several parameters - a parameter can be a function) and provide a result whenever it's called.

In JavaScript, a function is a value.

Named function

Declaration

A declared function is visible in the whole script.

function sayHello() {
console.log("hello")
}

The function name is usually a verb briefly describing the action. One function should do one action. Here's how to call it:

sayHello() // consols "hello"

Return

When reached, the return keyword makes the function stop and returns the results if any (default return value is undefined)

function checkAge(age) {  return age >= 18 ? true : false;}
checkAge(18) // returns true
checkAge(10) // returns false

A function can update variables without returning anything. For instance (from FreeCodeCamp) :

let sum = 0;

function addSum(num) {
  sum = sum + num;
}

addSum(3); // sum variable now equals 3
console.log(addSum(3)) // returns undefined

Default parameter value

Consider this function expecting three parameters:

function add(a, b, c) {  
return a + b + c
}

If a parameter is not passed on, it's value is considered as undefined.

add(4, 2) // returns NaN (Not a Number)

You can specify a default value if the parameter is omitted:

function addition(a, b, c = 0) {  
return a + b + c
}
add(4, 2) // returns 6

Rest parameter

The rest parameter (...param) is useful if we want a function to work with a variable number of arguments. Arguments passed this way are stored as an array. Check out this example:

function howMany(...args) {
  return args.length;
}
console.log(howMany(0, 1, 2)); // returns 3
console.log(howMany("string", null, [1, 2, 3], { })); // returns 4

Anonymous function

Anonymous or expressed functions are useful when we don't need to re-use them anywhere else in the code. It exists once it's reached. Here are two use-cases with possible syntax:

Calculate a value and pass it to a variable

Examples from FreeCodeCamp:

const myFunc = function() {
  const myVar = "value";
  return myVar;
}

With ES6 it can be shortened into an arrow function:

const myFunc = () => {
  const myVar = "value";
  return myVar;
}

Note that if we only want a value to be returned, then "return" keyword as well as brackets surrounding the code can be omitted.

const myFunc = () => "value";

If we need to pass arguments, the same principle as for named functions applies, except than parenthesis enclosing the parameter can be omitted if there's only one parameter:

const doubler = item => item * 2;
doubler(4);

const multiplier = (item, multi) => item * multi;
multiplier(4, 2);

Create an objet

Consider this object literal declaration (from FreeCodeCamp) which returns an object containing two properties:

const getMousePosition = (x, y) => ({
  x: x,
  y: y
});

Since ES6 a syntactic sugar exists. It eliminates the redundancy:

const getMousePosition = (x, y) => ({ x, y });

Here, x will be converted to x: x.



regex

March 15, 2023 Reading time: 11 minutes

These past few weeks I learned about regular expressions. Here's a recap! Almost all examples come from FreeCodeCamp.

Methods

Test method

let stringToTest = "a string";
let regEx = /pattern/;
regEx.test(stringToTest); // returns false

returns true or false depending if the pattern is found or not

Match method

let ourStr = "Regular expressions";
let ourRegex = /expressions/;
ourStr.match(ourRegex); // returns ["expressions"]

returns an extraction of the string that matches the provided pattern.

Replace method

let wrongText = "The sky is silver.";
let silverRegex = /silver/;
wrongText.replace(silverRegex, "blue"); // returns "The sky is blue"

searches for the described pattern and replacing it by a value of your choice.

You can also access capture groups in the replacement string with dollar signs ($) (see group capture in Patterns/Group elements/Reuse group).

"Code Camp".replace(/(\w+)\s(\w+)/, '$2 $1'); // returns "Camp Code"

Positive and negative lookahead

This is actually not a method but a special pattern to look ahead in the string for patterns further along. It won't match the element.

Use (?=...) to verify the element ("...") is there

Use (?!=...) to verify the element ("...") is not there

let quit = "qu";
let noquit = "qt";
let quRegex= /q(?=u)/;
let qRegex = /q(?!u)/;
quit.match(quRegex); // returns ["q"] ("u" is there)
noquit.match(qRegex); // returns ["q"] ("u" is not there)

Greedy vs lazy matching

This is not a method either but note that regular expressions are by default greedy meaning they will find the longest possible part of a string that fits the regex pattern and returns it as a match.

let string = "titanic";
let regEx = /t[a-z]*i/;
string.match(regEx); // returns "titani"

You can use ? to change it to lazy matching meaning the regular expression will find the shortest possible part of the string.

let string = "titanic";
let regEx = /t[a-z]*?i/;
string.match(regEx); // returns "ti"

Flags

Append flag right after the end of a pattern (//) if you need to extend the search to the whole string and/or ignore letter case.

Global search

Use g flag to search or extract a pattern more than once.

let testStr = "Repeat, Repeat, Repeat";
let repeatRegex = /Repeat/g;
testStr.match(ourRegex); // returns ["Repeat", "Repeat", "Repeat"]

Ignore case

Use i flag to ignore letter case (ie the difference between uppercase and lowercase letters).

let repeatRegex = /ignorecase/i;

This regex can match the strings ignorecase, igNoreCase, and IgnoreCase.

Multiple flags

Just concatenate them, for instance

let regEx = /search/gi

Patterns

Define a character set (aka character class)

Define a character set between square brackets []

Inside, define a list of character or a range of characters, using a hyphen character - to seperate from and to elements. Letters and numbers can be combined.

let regEx1 = /aeiu/
let regEx2 = /[a-e]/
let regEx3 = /[3-9]/
let regEx4 = /[a-e3-9]/

let catStr = "cat";
let batStr = "bat";
let matStr = "mat";
let bgRegex = /[a-e]at/;
catStr.match(bgRegex); // returns ["cat"]
batStr.match(bgRegex); // returns ["bat"]
matStr.match(bgRegex); // returns null

Negate a character set

Add ^ at the beginning of the character set you want to negate

let regEx = /[^aeiou]/gi // matches everything that is not a vowel

Group elements

Use () to group elements

let testStr = "Pumpkin";
let testRegex = /P(engu|umpk)in/;
testRegex.test(testStr); // Returns true

Reuse group

A group is saved as a temporary "variable" that can be accessed within the same regex using a backlash and the number of the captured group (e.g. \1). The number corresponds to the position of their opening parentheses, starting at 1.

let repeatStr = "row row row your boat";
let repeatRegex = /(\w+) \1 \1/;
repeatRegex.test(repeatStr); // Returns true
repeatStr.match(repeatRegex); // Returns ["row row row", "row"]

Possible existence of an element

Use ? right after the element

let american = "color";
let british = "colour";
let rainbowRegex= /colou?r/;
rainbowRegex.test(american); // Returns true
rainbowRegex.test(british); // Returns true

Alternative element

Use | (OR operator) between each element

let regEx = /yes|no/

Any element

Use wildcard character . to match any one character

let humStr = "I'll hum a song";
let hugStr = "Bear hug";
let huRegex = /hu./;
huRegex.test(humStr); // returns true
huRegex.test(hugStr); // returns true

Litteral string

Type the string you're looking for between / and /

let testStr = "Hello, my name is Kevin.";
let testRegex = /Kevin/;
testRegex.test(testStr); // returns true

All letters, numbers and underscore

Use \w

let longHand = /[A-Za-z0-9_]+/;
let shortHand = /\w+/;

For everything but letters, numbers and underscore, use \W (short hand for [^A-Za-z0-9_])

All numbers

Use \d

let longHand = /[0-9]/;
let shortHand = /\d/;

For all non-numbers, use \D (short hand for [^0-9])

Whitespace characters

Use \s to look for whitespace, carriage return (\r), tab (\t), form feed (\f), new line (\n) and vertical tab (\v)

let longHand = /[\r\t\f\n\v]/;
let shortHand = /\s/;

For non-whitespace, use \S (shorthand for [^ \r\t\f\n\v])

Define beginning and/or end of a pattern

Beginning

Use ^ outside of a character set and at the beginning of the regex

let firstString = "Ricky is first and can be found.";
let notFirst = "You can't find Ricky now.";
let firstRegex = /^Ricky/;
firstRegex.test(firstString); // returns true
firstRegex.test(notFirst); // returns false

Ending

Use $ at the end of the regex

let theEnding = "This is a never ending story";
let storyRegex = /story$/;
storyRegex.test(theEnding); // returns true
let noEnding = "Sometimes a story will have to end";
storyRegex.test(noEnding); // returns false

Occurencies

One or more times

Use + right after the character than can be found one or more times

let string1 = "abc"
let string2 = "aabc"
let string3 = "abab"
let regEx = /a+/g
string1.match(regEx); // returns [ 'a' ]
string2.match(regEx); // returns [ 'aa' ]
string3.match(regEx); // returns [ 'a', 'a' ]

Zero or more times

Use * right after the character that can be found zero or more times

let soccerWord = "gooooooooal!";
let gPhrase = "gut feeling";
let oPhrase = "over the moon";
let goRegex = /go*/;
soccerWord.match(goRegex); // returns ["goooooooo"]
gPhrase.match(goRegex); // returns ["g"]
oPhrase.match(goRegex); // returns null

Number of matches

Exact number

Specify a certain number of patterns using curly bracket {}

let A4 = "haaaah";
let A3 = "haaah";
let A100 = "h" + "a".repeat(100) + "h";
let multipleHA = /ha{3}h/;
multipleHA.test(A4); // returns false
multipleHA.test(A3); // returns true
multipleHA.test(A100); // returns false

Lower number

To only specify the lower number of patterns, keep the first number followed by a comma.

let A4 = "haaaah";
let A2 = "haah";
let A100 = "h" + "a".repeat(100) + "h";
let multipleA = /ha{3,}h/;
multipleA.test(A4); // returns true
multipleA.test(A2); // returns false
multipleA.test(A100); // returns true

Lower and upper number

Put two numbers between the curly brackets, separated by a comma - for the lower and upper number of patterns.

let A4 = "aaaah";
let A2 = "aah";
let multipleA = /a{3,5}h/;
multipleA.test(A4); // returns true
multipleA.test(A2); // returns false

objects

February 25, 2023 Reading time: 8 minutes

Let's continue our exploration of data sets in JavaScript by having a look at the objects!

Store

An object is also a collection of data but in a structured way as it's stored by pairs of property (or key) / value. For instance:

const BOOK = {
title: "The Lord of the Rings",
  "volumes": 3,
"main characters": ["Frodo", "Aragorn"],
9: ["Fellows", "Nazgul"]
};

Notes:

  • properties can be strings or numbers. Here's their syntax:
    • single word (title, volumes): quotes can be omitted (JavaScript will automatically typecast them as strings if the object has any non-string properties)
    • several words ("main characters"): quotes must be added
    • numbers (9): just type the number
  • as values, an object can contain strings, numbers, booleans, arrays, functions, and objects.

Access

Via dot or bracket notation

To access the propertie's value, you can either use the dot or the bracket notation:

const TITLE = BOOK.title;
const VOLUMES = BOOK["volumes"];
const MAIN_CHARACTERS = BOOK["main characters"];
const NINE = BOOK[9]

You can use the dot notation if your property in a string of a single word. Otherwise, user the bracket notation with quotes for strings and without for numbers.

Via a variable

Properties stored as value of a variable can also be access with the bracket notation. For instance:

const MAIN_CHARACTERS = "main characters";
let charactersList = BOOK[MAIN_CHARACTERS];
console.log(charactersList);

will print

[ 'Frodo', 'Aragorn' ]

on the console.

This can be very useful for iterating through an object's properties.

Nested objects

The same principle applies to access to sub propertie's values, just continue to filter via bracket or dot notation until you reach your destination. For instance (from FreeCodeCamp):

const ourStorage = {
"desk": {
"drawer": "stapler"
},
"cabinet": {
"top drawer": {
"folder1": "a file",
"folder2": "secrets"
},
"bottom drawer": "soda"
}
};

ourStorage.cabinet["top drawer"].folder2; // returns string "secrets"
ourStorage.desk.drawer; // returns string "stapler"

Does this property exist?

To check if the property of a given object exists or not, use the .hasOwnProperty(propname) method. It returns true or false if the property is found or not. For instance:

BOOK.hasOwnProperty("title"); 
BOOK.hasOwnProperty("author");

The first hasOwnProperty returns true, while the second returns false.

Note: always use quotes for string properties, otherwise an error is thrown.

Extract

Generate an array of all object keys

Use Object.keys() method. It takes an object as the argument and returns an array of strings representing each property in the object. The order is first all non-negative integer keys in ascending order by value, then other string keys in ascending chronological order of property creation. For instance:

Object.keys(BOOK) // returns [ '9', 'title', 'volumes', 'main characters' ]

Generate an array of all object values

Same principle. Use Object.values() method.

Object.values(BOOK) // returns [ [ 'Fellows', 'Nazgul' ], 'The Lord of the Rings', 3, [ 'Frodo', 'Aragorn' ] ]

Generate an array of all object key/value pairs

Same principle. Use Object.entries() method.

Object.entries(BOOK) //returns [ [ '9', [ 'Fellows', 'Nazgul' ] ], [ 'title', 'The Lord of the Rings' ], [ 'volumes', 3 ], [ 'main characters', [ 'Frodo', 'Aragorn' ] ] ]

Iterate through

Use a for...in statement. It looks like this:

for (let item in BOOK) {
  console.log(item);
} // logs 9, title, volumes, main characters, each value in its own line

Here, "item" is a variable we define - it could be any name. Its value will change at each iteration.

Use destructuring assignment

The example comes from FreeCodeCamp.

Consider this object:

const user = { name: 'John Doe', age: 34 };

To extract both values and assign them to variables you could use:

const { name, age } = user; 

Read it as: "create constants named "name" and "age" containing values from "name" and "age" properties in "user" object". This is a shorthand equivalent of

const name = user.name;
const age = user.age;

A console.log on name and age would return John Doe and 34, each on its own line

Manipulate

Prevent mutation

const declaration can by bypassed. To protect data from mutation, use Object.freeze() function. The argument would be the object you'd like to freeze. For instance (from FreeCodeCamp):

let obj = {
  name:"FreeCodeCamp",
  review:"Awesome"
};
Object.freeze(obj);
obj.review = "bad";
obj.newProp = "Test";

obj.review and obj.newProp assignments will result in errors and the object wouldn't change.

Update or add a value

Proceed like any other variable; using dot or bracket notation. For instance:

BOOK["main characters"][1] = "Sam";
BOOK["main characters"][2] = "Bill";
console.log(BOOK["main characters"]);

will print

[ 'Frodo', 'Sam', 'Bill' ]

on the console.

Append a property

Proceed just like you would for updating. For instance:

BOOK.format = "";
BOOK["number of copies"] = 100;
BOOK[5] = "Hello";

BOOK object will now look like this:

{
'5': 'Hello', '9': [ 'Fellows', 'Nazgul' ], title: 'The Lord of the Rings', volumes: 3, 'main characters': [ 'Frodo', 'Aragorn' ],
format: '', 'number of copies': 100
}

Order has not much importance from an object perspective because you're not using indexes to access data. But if this is important, consider using the spread operator (I'll probably write a blog entry later on this subject). Note that number properties order themselves at the beginning of the object.

Delete a property

User the delete keyword and then target your property according to it's format. For instance:

delete BOOK.format;
delete BOOK["number of copies"];
delete BOOK[5];

create or update project on GitHub

February 19, 2023 Reading time: 3 minutes

This is a personal step by step procedure to be updated.

Create (via command lines)

  1. open a terminal

  2. get the path to your project folder stored on your device

  3. write cd (for change directory) and then the path. For instance:
    cd Documents/www/project
  4. initialize the repository
    git init
  5. push all files (.) from this /project folder into staging (wait line)
    git add .
  6. push the package from staging to local repository and provide a message into quotes
    git commit -m "initial commit"
  7. create distant repository on GitHub (New repository) and copy the URL (https://github.com/username/project.git)

  8. push the package from local repository to distant repository

    1. indicate which repository you are aiming (replace "URL" by the one you copied on step 7)
      git remote add origin URL
    2. push it
      git push -u origin master
    3. enter your username and token

  9. verify result on GitHub

Update

via Code - OSS

via Command lines

  1. open a terminal

  2. get:
  3. write cd (for change directory) and then the path. For instance:
    cd Documents/www/project
  4. push all files (.) from this /project folder into staging (wait line)
    git add .
  5. push the package from staging to local repository and provide a message into quotes
    git commit -m "changed this"
  6. push the package from local repository to distant repository

    1. indicate which repository you are aiming (replace "URL" by the one you copied on step 2). Branch "master" and URL are optional
      git remote add master URL
    2. push it. Branch "master" is optional
      git push -u master
    3. enter your username and token

  7. verify result on GitHub


arrays

February 7, 2023 Reading time: 9 minutes

I learned a few things about JavaScript on OpenClassrooms (taking Apprenez à programmer avec JavaScript Écrivez du JavaScript pour le web courses). I didn't know it then but I was actually looking for DOM manipulation for my Qwixx project. Anyway, I'm refreshing my newbie knowledge by taking FreeCodeCamp JavaScript Algorithms and Data Structures course and here is a recap about arrays.

Store

An array can store multiple pieces of data in a single variable. Each entry is separated by a comma and nested into square brackets. Just like this:

const SANDWICH = ["peanut butter", 1, true, ["bakery", "home-made"]];

An array containing another array is also called a multi-dimensional array. An array can also contain objects.

Access

"peanut butter" 1 true ["bakery", "home-made"]
0 1 2 3

Arrays use zero-based indexing, so the first element in an array has an index of 0. Use square bracket notation to get the data associated to the index. For instance:

console.log(SANDWICH[0]);
const EATEN = SANDWICH[1];
console.log(EATEN);

will print "peanut butter" string and 1 number.

Note that additional pair of brackets refers to the next level of entries inside.

const BOUGHT_IN = SANDWICH[3][0];
console.log(BOUGHT_IN);

will print "bakery".

Check for the presence of an element

Use indexOf() method. It returns -1 if the item is not found. For instance:

SANDWICH.indexOf('peanut butter'); // returns 0 
SANDWICH.indexOf('butter'); // returns -1

Call for all items of an array

Use spread operator (...). For instance (from FreeCodeCamp):

const arr = [6, 89, 3, 45];
const maximus = Math.max(...arr); // maximus has the value of 89

Iterate through

Use a for loop. It looks like this:

let array = [1, 2, 3]
for (let i = 0; i < array.length; i++) {
console.log(array[i])
} // logs 1, 2, 3, each on its own line

Manipulate

Update data

Even if an array is defined as a const its entries are mutable. From our example,

SANDWICH[0] = "houmus";

SANDWICH now has the value

["houmus", 1, true, ["bakery", "home-made"]];

Append data

Onto the end of an array

Use push() method. It takes one or more parameters and "pushes" them onto the end of an array. For instance:

const arr = [1, 2, 3];
arr.push(4);

arr now has the value [1, 2, 3, 4]

Onto the beginning of an array

Use unshift() method. For instance:

const arr = [1, 2, 3];
arr.unshift(0);

arr now has the value [0, 1, 2, 3]

Somewhere specific

Use splice() method.

First argument: the index at which to begin deleting elements
Second argument (optional):  the number of elements to be deleted
Third argument (optional): items to insert starting at that same index, searated by a comma

For instance (example from FreeCodeCamp):

const numbers = [10, 11, 12, 12, 15];
const startIndex = 3;
const amountToDelete = 1;
numbers.splice(startIndex, amountToDelete, 13, 14);
console.log(numbers); // returns [ 10, 11, 12, 13, 14, 15 ]

Append elements from another array

User spread operator (...). For instance (example from FreeCodeCamp):

let arrayToAppend = ['sage', 'rosemary', 'parsley', 'thyme'];
let mainArray = ['basil', 'cilantro', ...arrayToAppend, 'coriander'];

mainArray now has the value ['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']

Remove data

From the end of an array

Use pop() method. For instance:

const arr = [1, 2, 3];
arr.pop();

arr now has the value [1, 2]

From the beginning of an array

Use shift() method. For instance:

const arr = [1, 2, 3];
arr.shift();

arr now has the value [2, 3]

Note: removed data can be returned if assigned to a variable. For instance:

const arr = [1, 2, 3];
let removedNumber = arr.pop();
let one = arr.shift();

removedNumber has the number 3 as a value and one, 1

Somewhere specific

You can also use splice() method!

First argument: the index at which to begin deleting elements
Second argument (optional):  the number of elements to be deleted

For instance (from FreeCodeCamp):

let array = ['today', 'was', 'not', 'so', 'great'];
array.splice(2, 2); // array now has the value ['today', 'was', 'great']

Here we remove 2 elements, beginning with the third element (at index 2). array would have the value

Note: removed data can be returned if assigned to a variable.

Copy an array

I realized it was not working like classic variables like these:

let a = "first variable"; // a contains "first variable" string
let b = a; // a and b contain "first variable" string
b = "second variable"; // a contains "first variable" and b "second variable" string

let array1 = [1, 2, 3]; // array1 contains [1, 2, 3] array
let array2 = array1; // array1 and array2 contain [1, 2, 3] array
array2.unshift(0); // array1 and array2 contain [0, 1, 2, 3] array

Here, array2 behaves just like another pointer to the same object. Modifying array2 will modify array1 and inversely. So how can we copy an array? Here are several methods:

With spread operator

For instance:

let originalArray = ['great', 'awesome', 'super', 'wonderful'];
let copiedArray = [...originalArray];

originalArray remains unchanged and copiedArray has the same elements as originalArray.

With slice() method

With slice() method, we can copy or extract a given number of elements to a new array, leaving the original array unchanged. It takes 2 parameters:

First argument: the index at which to begin extraction
Second argument (optional):  the index at which to stop extraction (not included)

For instance (example from FreeCodeCamp):

let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];
let todaysWeather = weatherConditions.slice(1, 3); // todaysWeather is ['snow', 'sleet']