Asked 7 years ago
28 Jan 2017
Views 1603
fatso

fatso posted

memory leak in JavaScript

what is memory leak in JavaScript ? how can i prevent it ?
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

Mostly programming / script Language have its own memory management module , where it work as garbage collector which free memory block which is not in use , if this not happen properly than memory stack increase and sometime result is application crash .

when we initialize a variable which is not in use and if it not freed by program it will remain until program run end.so as increase of unused variable / program data , memory use also increase.which is cause memory leak

JavaScript code ::


function dd(){ 
logr='me local';
}
dd();
console.log(logr);// me local 


in above example we defined the variable in function it look local and should be garbage collected in the end of function run but when we do acess of it at after run of the function . it is still in memory and it will remain until the program end.its called memory leak .
let me explain how it can be avoid

function dd(){ 
var logr='me local';
}


in above function we use var to make it local if you do not define with var than JavaScript make it global which is not expected and it cause memory leak.so do care of when you define variable .


shabi

shabi
answered Nov 30 '-1 00:00

each language have Garbage collection system which release memory which is not used .

garbage collection algorithm , collect memory of object which have zero reference
which reduce the memory leak

jqueryLearner

jqueryLearner
answered Nov 30 '-1 00:00

let me show you how memory leak happen and how can we solve it
look at following code .
1. foo function

function foo(){
var d='data';
}

2. second foo function

function foo(){
d='data';
}


it seem both same . but there is minor difference is that in first variable d is local variable and in second function variable d is global function

in second function it is global variable like window.d='data'

so its called memory leak because we missed var to define variable

How to solve this memory leak in javascript ?

'use strict'; at starting of the code at javascript programming
it prevent global variable declaration at without asking ,

Post Answer