google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






10 astuces Javascript petits, il faut ma Dans ce tutoriel JavaScript article, l'auteur propose une dizaine de petites JavaScript conseils et astuces, Principalement destin


�tiquette: 10, Javascript astuces, Si Master, d

G�n�rez vos vid�os d'entreprise par l'IA avec la voix ou simplement du texte



Votre premi�re application vid�o AI GRATUITE ! Automatisez votre premi�re vid�o AI. Cr�ez votre vid�o professionnelle en 5 minutes gr�ce � l'IA. Aucun �quipement ni comp�tence en montage vid�o requis. Production vid�o sans effort pour les sp�cialistes du marketing de contenu.
Application vid�o AI ILLIMIT�E gratuite � port�e de main

6. Testing existence of property

This issue can be approached at least from two directions. Either we check whether property exists or we check the type of property. But always avoid these small mistakes:

// BAD: This will cause an error in code when foo is undefined
if (foo) {
	doSomething();
} 

// GOOD: This doesn't cause any errors. However, even when
// foo is set to NULL or false, the condition validates as true
if (typeof foo != "undefined") {
	doSomething();
}

// BETTER: This doesn't cause any errors and in addition
// values NULL or false won't validate as true
if (window.foo) {
	doSomething();
}

However, there may be situations, when we have deeper structure and proper checking would look like this:

// UGLY: we have to proof existence of every
// object before we can be sure property actually exists
if (window.oFoo && oFoo.oBar && oFoo.oBar.baz) {
	doSomething();
}

7. Passing arguments for function

When function has both required and optional parameters (arguments), eventually we may end up with functions and function calls looking like this:

function doSomething(arg0, arg1, arg2, arg3, arg4) {
...
}

doSomething('', 'foo', 5, [], false);

It's always easier to pass only one object instead of several arguments:

function doSomething() {
	// Leaves the function if nothing is passed
	if (!arguments[0]) {
		return false;
	}

	var oArgs	= arguments[0]
		arg0	= oArgs.arg0 || "",
		arg1	= oArgs.arg1 || "",
		arg2	= oArgs.arg2 || 0,
		arg3	= oArgs.arg3 || [],
		arg4	= oArgs.arg4 || false;
}

doSomething({
	arg1	: "foo",
	arg2	: 5,
	arg4	: false
});

This is only a rough example of passing an object as an argument. For instance, we could declare an object with name of the variable as keys and default values as properties (and/or data types).

8. Using document.createDocumentFragment()

You may need to dynamically append multiple elements into document. However, appending them directly into document will fire redrawing of whole view every time, which causes perfomance penalty. Instead, you should use document fragments, which are appended only once after completion:

function createList() {
	var aLI	= ["first item", "second item", "third item",
		"fourth item", "fith item"];

	// Creates the fragment
	var oFrag	= document.createDocumentFragment();

	while (aLI.length) {
		var oLI	= document.createElement("li");

		// Removes the first item from array and appends it
		// as a text node to LI element
		oLI.appendChild(document.createTextNode(aLI.shift()));
		oFrag.appendChild(oLI);
	}

	document.getElementById('myUL').appendChild(oFrag);
}

9. Passing a function for replace() method

There are situations when you want to replace specific parts of the string with specific values. The best way of doing this would be passing a separate function for method String.replace().

Following example is a rough implementation of making a more verbose output from a single deal in online poker:

var sFlop	= "Flop: [Ah] [Ks] [7c]";
var aValues	= {"A":"Ace","K":"King",7:"Seven"};
var aSuits	= {"h":"Hearts","s":"Spades",
			"d":"Diamonds","c":"Clubs"};

sFlop	= sFlop.replace(/\[\w+\]/gi, function(match) {
	match	= match.replace(match[2], aSuits[match[2]]);
	match	= match.replace(match[1], aValues[match[1]] +" of ");

	return match;
});

// string sFlop now contains:
// "Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"

10. Labeling of loops (iterations)

Sometimes, you may have iterations inside iterations and you may want to exit between looping. This can be done by labeling:

outerloop:
for (var iI=0;iI<5;iI++) {
	if (somethingIsTrue()) {
		// Breaks the outer loop iteration
		break outerloop;
	}

	innerloop:
	for (var iA=0;iA<5;iA++) {
		if (somethingElseIsTrue()) {
			// Breaks the inner loop iteration
			break innerloop;
		}

	}
}

Afterwords

Go ahead and comment! Did you learn anything new? Do you have good tips to share? I'm always delighted for sharing information about all the little details in Javascript.

And if you want to familiarize with Javascript irregularities, I suggest you visiting at wtfjs :).

AIVideo-App.com
Générez vos vidéos d'entreprise par l'IA avec la voix ou simplement du texte

chatGPTaz.com
Parlez à ChatGPT dans votre langue maternelle

AppAIVidéo
Votre première application vidéo AI GRATUITE

Deepfake Video
Deepfake AI Video Maker

Deepfake
Deepfake AI Video Maker

AI Deep Fake
Deepfake AI Video Maker

AIvidio
AI Video Mobile Solutions

AIvideos
AI Video Platform & Solutions

AIvedio
AI Video App Maker

Artificial General Intelligence
Ai and higher level Artificial General Intelligence (AGI)

Artificial General Intelligence
Ai and higher level Artificial General Intelligence (AGI)

Faceswap AI en ligne
Échangez des visages, des vidéos, des photos et des GIF instantanément avec de puissants outils d'IA - Faceswap AI Online GRATUIT

Faceswap AI en ligne
Échangez des visages, des vidéos, des photos et des GIF instantanément avec de puissants outils d'IA - Faceswap AI Online GRATUIT

Faceswap AI en ligne
Échangez des visages, des vidéos, des photos et des GIF instantanément avec de puissants outils d'IA - Faceswap AI Online GRATUIT

Powerful AI Presentation PPT Maker for FREE
Build an impressive presentation with our free online AI presentation app

Your next top AI Assistant
Claude AI, developed by Anthropic

Your next top AI Assistant
Claude AI, developed by Anthropic

Temu gratuit 500 $ pour les nouveaux utilisateurs
Claim Free Temu $500 Credit via Affiliate & Influencer Program

Crédits publicitaires TikTok gratuits
Maîtrisez les publicités TikTok pour le marketing de votre entreprise

Dall-E-OpenAI.com
Générez automatiquement des images créatives avec l'IA

chatGPT4.win
Parlez à ChatGPT dans votre langue maternelle

Premier produit d'intelligence artificielle d'Elon Musk - Grok/UN.com
Parlez au chatbot Grok AI dans votre langue

Outily.win
Centre d'outils ouvert et gratuit, utilisable par tous et pour tous, avec des centaines d'outils

GateIO.gomymobi.com
Airdrops gratuits à réclamer et à partager jusqu'à 150 000 $ par projet

iPhoneKer.com
Économisez jusqu'à 630 $ à l'achat d'un nouvel iPhone 16

Acheter le robot Tesla Optimus
Commandez votre robot Tesla Bot : Optimus Gen 2 dès aujourd'hui pour moins de 20 000 $

JavaScript par jour


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web