I recently just started learning the basics of JavaScript, and I’d like to share something I’ve learnt so far off hand. I’ll be writing about functions in JavaScript.
A function is used to perform a task or calculate a value in JavaScript. It is one of the non-primitive data types that we have in JavaScript(the other two are objects and arrays).
There are two ways we can write a function syntax in JavaScript, and they are;
- Function(){}
- Const x = ()=>{} (here, x denotes the name of the function we’re declaring
Both ways are syntactically correct.
The second one is called the arrow function.
From the function syntax, we can see that both the parentheses () and curly braces {} are constant. The parentheses is used to accept the parameters, while the curly braces accepts the logic or argument.
It is very important to note that a function isn’t complete if it isn’t called or invoked, else the code will not run.
Below is an example to illustrate everything I’ve said.
Question: write a function sum that takes in two parameters a,b and adds them together.
Solution:
const sum = (a,b) => {
let add = a + b;
console.log(“The sum is: ” + add)
}
sum(3,5)
—————————————————————————————————
The output will be 8.
Top comments (0)