Friday, September 9, 2022

push Array Method | JavaScript Tutorial 09-2022 ~ Samuel F Campbell

                                 
JavaScript
03-10-2023 Sat 


Learning to code:
  • opens new doors
  • creates new hobbies
  • launches new careers
  • develops new skills
  • expands your network


Glossary:
The data types in JavaScript include numbers, strings, booleans, arrays, and objects.


Number:
In JavaScript, numbers can be whole (such as 10) or contain a decimal (such as 10.5).

EXAMPLE:

var numberOfApples = 10;

var temperature = 74.6;

The numberOfApples and temperature variables both store numbers.


String

Strings store text, such as letters, words, symbols, and spaces
Strings are surrounded by quotation marks.

EXAMPLE:

var message = 'Hello world';

The message variable stores the string 'Hello world'.


Boolean

A boolean stores the value true or false.

EXAMPLE:

var isLearningToCode = true; 

var shouldWearSocksWithSandals = false;

It’s true that you’re learning to code, but it’s false that sandals should be worn with socks.


Array
An array is a list containing multiple items. The items can be different data types: numbers, strings, and even other arrays. An array inside another array is called a nested array.

EXAMPLE:

var exampleArray = ['blue', 'orange', 5, 10, [50, 10]];

exampleArray has 5 items. It contains strings, numbers and an array; which itself has two items that are numbers.



Array Indexing
Array indexing provides a way to access a specific item in an array. 
In most programming languages, including JavaScript, array indices start at 0
For example, the first item in an array is at index 0, the second item is at index 1, etc.

 EXAMPLE:
var groceries = ['apples', 'bananas', 'oranges'];

var fruit = groceries[2];

The fruit variable holds the third item in the array, 'oranges'.



Object
An object stores an unordered list of properties
Each property is a key:value pair. 
The key stores the property's name
The value can be any data type, such as a number, string, array, or even another object.

EXAMPLE:

var apple = {

  variety: 'red',

  pricePerPound: 1.25,

};

variety and pricePerPound are properties of the apple object.

'red' is the value stored in the variety property.

1.25 is the value stored in the pricePerPound property.



Object Dot Notation
Dot notation is one way to access a property of an object. To use dot notation, write the name of the object, followed by a dot (.), followed by the name of the property.

EXAMPLE:

var cat = {

  name: 'Moo',

  age: 5,

};

console.log(cat.name);

This code will print the name property of the cat object,  'Moo'.


Object Bracket Notation

Bracket notation is another way to access a property of an object. 
To use bracket notation, write the name of the object, followed by brackets []
Inside the brackets, write the property name as a string.

EXAMPLE:

var dog = {

  name: 'Lady',

  friends: ['Moo','Bowie'],

};

console.log(dog['name'])

This code will print the nameproperty of the dog object, 'Lady'.

Undefined

When a variable has not been assigned a value, its value is undefined.

EXAMPLE:

var fruit;

console.log(fruit);

The fruit variable doesn’t have a value so this code will print undefined.

:::::::::::::::



Functions

A function is a reusable block of code that tells a computer to do a specific thing. Functions usually take information, process it, and return a result.
Function call
When you call a function, you’re telling the computer to run a specific block of code. 
To call a function, write that function’s name, followed by parentheses ( )
Inside the parentheses, you can add any necessary arguments.

An argument is extra information given to a function that tells it how it should run.

EXAMPLE:

sayHello();

printSum(1,2);

The sayHello() function call tells the computer to run the sayHello function. It doesn’t take any arguments.

The printSum(1,2) function call tells the computer to run the printSum function using the numbers 1 and 2 as the necessary arguments.

Function declaration

A function declaration is used to create a function.
It is comprised of three parts: 
  1. The name of the function
  2. Optional parameters ( ) that behave like variables inside the function. Parameters tell the function what to do with the arguments it’s given.
  3. The block of code {} to run when the function is called.

EXAMPLE:

function addNumbers(num1, num2) {

  var answer = num1 + num2;

  return answer;

}

The addNumbers function adds 2 numbers together and then returns the result.


Callback Function


When a function is used as an argument to another function, it’s called a callback function. You can tell a function is a callback when it doesn’t have parentheses after its name.

EXAMPLE:

let array = [2, 4, 6];

function print(num) {

  console.log(num);

}

array.forEach(print);

The array method .forEach() takes the callback function print() as an argument, and will apply that function to each item in the array.



Arrow Function
An arrow function is a compact way to write a function declaration
It uses () => {} instead of the function keyword.

EXAMPLE:

function add(num1, num2) {

  return num1 + num2; 

};

var arrowFunctionAdd = (num1, num2) => { 

  return num1 + num2; 

};

Here is an example of a function that takes 2 numbers and adds them together; and the same code using an arrow function.


::::::::::::::::::::::::::::::::::::::::

Search and Locate


Array Methods - Learning different ways to search arrays, combine elements, transform elements, using arrow functions.


Use a classic for loop to iterate over every other element in an array.


Classic For Loop


In JavaScript, a classic for loop repeats the same code inside the blook { } a specified number of times. It is defined in three parts.


The first part happens before the loop starts and defines a looping variable
   (var i = 0;).


The second part is a test that determines if the loop should keep repeating
    (i < 10;).


And The third part updates the looping variable each time the loop repeats.
(i = i + 1).


Example code 
print('The loop will go as long for
(var i = 0; i < 10;
i = i + print(i);
}

:::::::::::::::::


In this example, the looping variable (i) starts at 0. The code in the block { } will keep repeating while i is less than 10. And i is increased by 1 each loop. The code prints out the message, the loop will go as long as i is less than 10.", and then it prints the numbers 0 through 9


In this lab I will use the classic for loop to iterate over every other element in an array.


A Classic For Loop has 3 parts.


1. A start position that declares a variable and gives it a value.


2. A test that keeps a classic for loop running as long as long as the test is true.


3. An update operation that changes the variable after each iteration.


The closingTimes array contains a list of times as strings. Update every other element in the array with a classic for loop.


Instructions:
* Inside the setup ( ) of the classic for loop,
change the
i += 1 to i += 2
* inside the code block { }, change 5 pm to "9pm"


My Code

Import  {closingTimes}    from' grasshoper.store' ;

console.log (closingTimes);


for (let i = 0; i < closingTimes
.length; i += 1) {
closingTimes [i] = '5pm'

}
console.log (closingTimes);

My Resulting Solution
> 5pm, 5pm, 5pm, 5pm, 5pm,5pm, 5pm
> 9pm, 5pm, 9pm, 5pm, 9pm,5pm, 9pm

Congrats!
You used a classic for loop to iterate over every other element.
::::::::::::::
Next
:::::::::::::::

Use the indexOf method to
find the indedex number of your favorite cereal 🥣 


The bestCereals array contains a list of the the top cereals in the store. Since array elements are numbered from 0 the best ranking cereal is the one at indexed 0.


Instructions 

To see what rank your favorite cereal is: 

Chang the argument of the indexOf( )  to favorite


Example Solution 

< 3

My Solution 
< -2

Your code 

Import { bestCereals } from '
 grasshopper.store' ;

  let  favorite  =  ' ant  bran '

   console.log(bestCereals.includes(
favorite) ? bestCereals.indexOf( ' mosquito bits ') : '
Not on the list . ');

My Resulting Solution 
> 3

Congrat!

Used the indexOf( ) array method to get, the ranking of a favorite cereal 🥣 
:::::::::::::   

03-10-2023Sat 22:00 
Next


ç==============è

  A Milk Mistake

The lastIndexOf method is similar to indexOf,

but searches in reverse from end of an array.

If no element is found. .lastIndexOf will return – 1.

 

When checking g out of the grocery store, milk was accidentally scanned twice. Find the index of the second milk 🥛

 using lastIndexOf( )

 

 

 

Instructions:  

            Inside parentheses .lastIndexOf(  ):

 

Ø  Add milk as a argument.

 

 

 

import { cart } from '

grasshopper.store' ;

 

console.log( cart ) ;

 

let index = cart .lastIndexOf ( '

eggs ' )

 

console.log (

' The extra item is at index :   +

Index )

 

 

let index = cart .lastIndexOf ( 'milk' )

 

 

Sample Code Results:

 

>> flour, milk, milk, eggs

>> flour, milk, milk, eggs

 

My Code Results :

 

>> flour, milk, milk, eggs

>> The extra ingredient is at index: 2

 

 

 

 

Congrats!

You used a lastIndexOf ( ) array method to find

the last index element in an array.

03-27-2023 Web 18:00






import {cart} from 
'grasshopper.store' console.log (cart) ;
let index = cart .lastIndexOf ('milk')
console.log ('The extra item is at 



Congrats!
You used a lastIndexOf ( ) array method to find the last 
03-27-2023 Web 18:00 

::::::::::::::::::::::

Javascript TesterJavaScript Tester                          JavaScript tester - online javascript tester for:
  •  editing and 
  • testing your javascript code snippets
Use the javascript tester to quickly test your javascript functions and code. 

For more complex testing of code/html/css use something like:
  • CodePen or 
  • JSFiddle
  • The javascript tester will 
  • highlight syntax errors in the editor and 
  • provide meaningful messages to 
  • help debug your code
  • Runtime errors are shown below the editor.


const dogs = [
    {age: 10, name: 'Fido'}, 
    {age: 14, name: 'Bowser'},
    {age: 16, name: 'Rusty'}
  ];

  dogs.map(dog => dog.name);

Result of evaluating code:


["Fido","Bowser","Rusty"]

::::::::::::::::::::::::::::::::::::::::

var dog = {

  name: 'Lady',

  friends: ['Moo','Bowie'],

};

console.log(dog['name'])

  

Result of evaluating code:

"Lady"

undefined


The tester will evaluate your code and print the result to result section under the editor. The basic idea is you enter snippets of code you want to test with. The last expression will get printed as a result. The last expression should not contain a "return" statement or a variable assignment. It should just be an expression. You can also add additional console.log messages at various points in you code and these will also be shown in the result section on this page.

For example:

const dogs = [
    {age: 10, name: 'Fido'}, 
    {age: 14, name: 'Bowser'},
    {age: 16, name: 'Rusty'}
  ];

  dogs.map(dog => dog.name);        
            
Try adding the following before the last statement and then click Run again:
console.log(dogs.map(dog => {return {name: dog.name}}));

Great for testing ideas or running simple code snippets...

This editor works entirely in your browser (it uses the Ace embeddable code editor.). Your code is not sent to any server. If you close the browser or tab the current state of the editor is saved. If you don't want your code saved remember to clear the editor before closing. We value Privacy!

See below for keyboard shortcuts

JavaScript Tester - Features

Syntax highlightingThere are two components to syntax highlighting:
  • Tokenization: Breaking text into a list of tokens
  • Theming: Using themes or user settings to map the tokens to specific colors and styles

Tokenization#

The tokenization of text is about breaking the text into segments and to classify each segment with a token type.

VS Code's tokenization engine is powered by TextMate grammars. TextMate grammars are a structured collection of regular expressions and are written as a plist (XML) or JSON files. VS Code extensions can contribute grammars through the grammars contribution point.

The TextMate tokenization engine runs in the same process as the renderer and tokens are updated as the user types. Tokens are used for syntax highlighting, but also to classify the source code into areas of comments, strings, regex.

Starting with release 1.43, VS Code also allows extensions to provide tokenization through a Semantic Token Provider. Semantic providers are typically implemented by language servers that have a deeper understanding of the source file and can resolve symbols in the context of the project. For example, a constant variable name can be rendered using constant highlighting throughout the project, not just at the place of its declaration.

Highlighting based on semantic tokens is considered an addition to the TextMate-based syntax highlighting. Semantic highlighting goes on top of the syntax highlighting. And as language servers can take a while to load and analyze a project, semantic token highlighting may appear after a short delay.



Automatic indent and outdent

Indenting syntax

Last Updated: 2021-03-22

You can indent or outdent selected lines of syntax and you can automatically indent selections so that the syntax is formatted in a manner similar to syntax pasted from a dialog box.

  • The default indent is four spaces and applies to indenting selected lines of syntax as well as to automatic indentation. You can change the indent size from the Syntax Editor tab in the Options dialog box.
  • Note that using the Tab key in the Syntax Editor does not insert a tab character. It inserts a space.

Indenting text

  1. Select the text or position the cursor on a single line that you want to indent.
  2. From the menus choose:

    Tools > Indent Syntax > Indent

You can also indent a selection or line by pressing the Tab key.

Outdenting text

  1. Select the text or position the cursor on a single line that you want to outdent.
  2. From the menus choose:

    Tools > Indent Syntax > Outdent

Automatically indenting text

  1. Select the text.
  2. From the menus choose:

    Tools > Indent Syntax > Auto Indent

When you automatically indent text, any existing indentation is removed and replaced with the automatically generated indents. Note that automatically indenting code within a BEGIN PROGRAM block may break the code if it depends on specific indentation to function, such as Python code containing loops and conditional blocks.

Syntax formatted with the auto-indent feature may not run in batch mode. For example, auto-indenting an INPUT PROGRAM-END INPUT PROGRAMLOOP-END LOOPDO IF-END IF or DO REPEAT-END REPEAT block will cause the syntax to fail in batch mode because commands in the block will be indented and will not start in column 1 as required for batch mode. You can, however, use the -i switch in batch mode to force the Batch Facility to use interactive syntax rules. See the topic Syntax Rules for more information.

Live syntax checkingOct 14, 2006 — The latest addition is Live Syntax Checking. This is particularly useful for people who are starting out with PowerShell





Handles large documents
Search and replace with regular expressions (Ctrl-F)
Highlight matching parentheses
Drag and drop text using the mouse
Line wrapping
Code folding
Multiple cursors and selections
Cut, copy, and paste functionality

The following video gives some color theory basics to help you with your selections.


Semantic Highlight Guide

Semantic highlighting is an addition to syntax highlighting as described in the Syntax Highlight guide. Visual Studio Code uses TextMate grammars as the main tokenization engine. TextMate grammars work on a single file as input and break it up based on lexical rules expressed in regular expressions.

Semantic tokenization allows language servers to provide additional token information based on the language server's knowledge on how to resolve symbols in the context of a project. Themes can opt in to use semantic tokens to improve and refine the syntax highlighting from grammars. The editor applies the highlighting from semantic tokens on top of the highlighting from grammars.

Here's an example of what semantic highlighting can add:

Without semantic highlighting:

without semantic highlighting

With semantic highlighting:

with semantic highlighting

Notice the color differences based on language service symbol understanding:

  • line 10: languageModes is colored as a parameter
  • line 11: Range and Position are colored as classes and document as a parameter.
  • line 13: getFoldingRanges is colored as a function




Editor Keyboard Shortcuts

Line Operations:



 
Windows/Linux     Mac                              Action

Ctrl-D                                  Command-D                                        Remove line

Alt-Shift-Down                   Command-Option-Down                     Copy lines down

Alt-Shift-Up                        Command-Option-Up                           Copy lines up

Alt-Down                            Option-Down                                       Move lines down

Alt-Up                                 Option-Up                                            Move lines up

Alt-Delete                           Ctrl-K                                                   Remove to line end

Alt-Backspace                   Command-Backspace                            Remove to linestart

Ctrl-Backspace    Option-Backspace, Ctrl-Option-Backspace        Remove word left

Ctrl-Delete             Option-Delete                                                    Remove word right

                            Ctrl-O                                                               Split line


Selection

Windows/LinuxMacAction
Ctrl-ACommand-ASelect all
Shift-LeftShift-LeftSelect left
Shift-RightShift-RightSelect right
Ctrl-Shift-LeftOption-Shift-LeftSelect word left
Ctrl-Shift-RightOption-Shift-RightSelect word right
Shift-HomeShift-HomeSelect line start
Shift-EndShift-EndSelect line end
Alt-Shift-RightCommand-Shift-RightSelect to line end
Alt-Shift-LeftCommand-Shift-LeftSelect to line start
Shift-UpShift-UpSelect up
Shift-DownShift-DownSelect down
Shift-PageUpShift-PageUpSelect page up
Shift-PageDownShift-PageDownSelect page down
Ctrl-Shift-HomeCommand-Shift-UpSelect to start
Ctrl-Shift-EndCommand-Shift-DownSelect to end
Ctrl-Shift-DCommand-Shift-DDuplicate selection
Ctrl-Shift-PSelect to matching bracket

Multicursor

Windows/LinuxMacAction
Ctrl-Alt-UpCtrl-Option-UpAdd multi-cursor above
Ctrl-Alt-DownCtrl-Option-DownAdd multi-cursor below
Ctrl-Alt-RightCtrl-Option-RightAdd next occurrence to multi-selection
Ctrl-Alt-LeftCtrl-Option-LeftAdd previous occurrence to multi-selection
Ctrl-Alt-Shift-UpCtrl-Option-Shift-UpMove multicursor from current line to the line above
Ctrl-Alt-Shift-DownCtrl-Option-Shift-DownMove multicursor from current line to the line below
Ctrl-Alt-Shift-RightCtrl-Option-Shift-RightRemove current occurrence from multi-selection and move to next
Ctrl-Alt-Shift-LeftCtrl-Option-Shift-LeftRemove current occurrence from multi-selection and move to previous
Ctrl-Shift-LCtrl-Shift-LSelect all from multi-selection

Go to

Windows/LinuxMacAction
LeftLeft, Ctrl-BGo to left
RightRight, Ctrl-FGo to right
Ctrl-LeftOption-LeftGo to word left
Ctrl-RightOption-RightGo to word right
UpUp, Ctrl-PGo line up
DownDown, Ctrl-NGo line down
Alt-Left, HomeCommand-Left, Home, Ctrl-AGo to line start
Alt-Right, EndCommand-Right, End, Ctrl-EGo to line end
PageUpOption-PageUpGo to page up
PageDownOption-PageDown, Ctrl-VGo to page down
Ctrl-HomeCommand-Home, Command-UpGo to start
Ctrl-EndCommand-End, Command-DownGo to end
Ctrl-LCommand-LGo to line
Ctrl-DownCommand-DownScroll line down
Ctrl-UpScroll line up
Ctrl-PGo to matching bracket
Option-PageDownScroll page down
Option-PageUpScroll page up

Find/Replace

Windows/LinuxMacAction
Ctrl-FCommand-FFind
Ctrl-HCommand-Option-FReplace
Ctrl-KCommand-GFind next
Ctrl-Shift-KCommand-Shift-GFind previous

Folding

Windows/LinuxMacAction
Alt-L, Ctrl-F1Command-Option-L, Command-F1Fold selection
Alt-Shift-L, Ctrl-Shift-F1Command-Option-Shift-L, Command-Shift-F1Unfold
Alt-0Command-Option-0Fold all
Alt-Shift-0Command-Option-Shift-0Unfold all



Other

Windows/Linux                       Mac                                                 Action
Tab                                           Tab                                                  Indent 
Shift-Tab                                  Shift-Tab                                        Outdent
Ctrl-Z                                        Command-Z                                   Undo       
Ctrl-Shift-Z, Ctrl-Y                   Command-Shift-Z, Command-Y   Redo 
Ctrl-,                                         Command-,                         Show the settings menu
Ctrl-/                                         Command-/                                     Toggle comment
Ctrl-T                                        Ctrl-T                                               Transpose letters
Ctrl-Enter                                 Command-Enter                              Enter full screen
Ctrl-Shift-U                               Ctrl-Shift-U                             Change to lower case
Ctrl-U                                        Ctrl-U                                      Change to upper case
Insert                                         Insert                                               Overwrite
Ctrl-Shift-E                               Command-Shift-E                           Macros replay
Ctrl-Alt-E                                                                                    Macros recording
Delete                                                                                             Delete
    ---                                          Ctrl-L                                                 Center selection