args js code example

Example 1: arrondi js

let x = 2.960024578;
let res = x.toFixed(2);
console.log(res);
//2,96

Example 2: js unspecified parameters

function my_log(...args) {
     // args is an Array
     console.log(args);
     // You can pass this array as parameters to another function
     console.log(...args);
}

Example 3: js array

var colors = [ "red", "orange", "yellow", "green", "blue" ]; //Array

console.log(colors); //Should give the whole array
console.log(colors[0]); //should say "red"
console.log(colors[1]); //should say "orange"
console.log(colors[4]); //should say "blue"

colors[4] = "dark blue" //changes "blue" value to "dark blue"
console.log(colors[4]); //should say "dark blue"
//I hope this helped :)

Example 4: arguments object in javascript

var sum = 0;
function addAll(){
    for (var i = 0; i<arguments.length; i++){
        sum+=arguments[i];
    }
    console.log(sum);
}

addAll(1, 2, 3, 4, 5, 6, 7, 8, 9,10); //we can provide inifite numbers as argument

Example 5: *args python javascript equivalent

//spread operator
a = [1, 2, 3]

function printArgs(args) {
	console.log(...args)
}

printArgs(a)
//=> 1 2 3

Example 6: how to access any argument in javascript

function example() {
	console.log(arguments);
  	console.log(arguments[0]);
} // Console outputs an array of each argument with its value

example('hi', 'hello'); 
// Outputs: 
// ['hi', 'hello']
// 'hi'