DEV Community

Pardeep Kashyap
Pardeep Kashyap

Posted on • Edited on

What is the Javascript Pure Function?

1.Pure function is the function that takes input returns a value without modifying data outsides of its scope

  1. Which Generate same output with the same parameters every time
var a=[1,2,3];

function impureJSFunction(array,value){
    array.unshift(value);
}

impureJSFunction(a,10)

console.log(a);
Enter fullscreen mode Exit fullscreen mode

Alt Text

This is not a Pure JS function as its affecting the outside array a[];

How javascript a Pure Javascript function?

var a=[1,2,3];

function pureJSFunction(array,value){
     return [...array,value] ;
}


console.log("pureUnshiftData",pureJSFunction(a,10))
Enter fullscreen mode Exit fullscreen mode

Alt Text

is this a pure JS function?

function myFunc(array,value){
    return [...array,value,Math.random()] ;
}

console.log("Is it pure ?",myFunc(a,10));
Enter fullscreen mode Exit fullscreen mode

Alt Text

//Answer is No Because it does not satisfy the second Point as it not returning same values with same parameters every time

//Answer is No Because it does not satisfy the second Point as it not returning same values with the same parameters every time

Learn Source - https://www.youtube.com/watch?v=fYbhD_KMCOg&t=311s

Top comments (1)

Collapse
 
craigmc08 profile image
Craig McIlwrath • Edited

You might want to check the formatting of this article. The formatting makes it kind of difficult to read.

  1. You start each text line with //, this isn't necessary on dev.to (this isn't a js file).

  2. There are code blocks so snippets of code can be syntax-highlighted and monospaced. You can do this by surrounding each snippet with triple backticks (`) . I can't figure out how to show you exactly how to write this, so check out this resource.

dev.to uses markdown to format articles, you should read more about it if my comment is confusing.

I hope this helps you!